A simple query on unix shell script

I want to write a script to go to particular path in file and run shell script from there.

what will be shell script for the same.

a possible solution could be:

#!/bin/bash

if [ -z $1 ]; then
  exit;
fi

current_directory=`pwd`

# 2nd call of the script
if [ "$1" == "$current_directory" ]; then
  ls -l
# first call of the script
else
  cd $1 2>/dev/null
  if [ $? -ne 0 ]; then
    echo "no such directory"
  else
    if [ "${0:0:1}" == "/" ]; then
      $0 `pwd`
    else
      $current_directory/$0 `pwd`
    fi
  fi
fi

This script needs to be called with one argument. That must be a directory name. The script will then change to that directory and do a simple ls -l.

1st check if there is one argument submited (if not quit)
2nd remember the current working directory
3rd check if current woring directory and the target directory (submited in $1) is identical.

  • If thats the case, just do an ls -l and then quit.
  • If this is not the case, change to the target directory. Check if cd was successfull and then run this script ($0) again with now the current directory as the argument.

The script itself resides still in the old directory (or somewhere else). Therefore a script call with a relative path would fail. So the old path before changing to the target directory must be submited as well to locate the script. If the script was called with an absolute path, $0 can be used without changes (will be located anyway).
You can ommit this problem if you put your script into your $PATH.

Some modification for the given script to handle spaces in paths, etc.:

#!/bin/ksh
[[ -z "${1}" ]] && { print "Please specify a path";return 1; }
[[ -d "${1}" ]] && { print "Specified path is a directory! You should specify a path to executable.";return 1; }
[[ -x "${1}" ]] || { print "Specified path is not executable!";return 1; }
typeset OldPwd=$(pwd)
typeset NewPwd="${1%/*}"
typeset ExecName="${1##/}"
typeset -i RC=0
# The file could be located in current directory, ex. `script.ksh script.ksh`
[[ -n "${NewPwd}" ]] && cd "${NewPwd}"
"${ExecName}"
RC=$?
print -- "Exited with status ${RC}"
# Usually `cd -` would work as well
cd "${OldPwd}"
return ${RC}

Note, that is probably not so important for you:
You should expect some problems with "current directory" if the file is a link. To obtain real directory that contain the executable, and not the link, you should do some more things. But this is probably not what you would like to do.