0
#!/usr/bin/ksh


if [ $# -ne 1 ]; then
        echo "[*]\t Please see usage..."
        echo "[*]\t Usage: $0 <store_number>"
        exit 1
fi


if [ -z "$1" ]; then
        echo "[*]\t Please see usage..."
        echo "[*]\t Usage: $0 <store_number>"
  exit 1
fi


Store_Number=$1
EPS_Directory="/apps/epsadmin_90000"$Store_Number"/EPS"


cd $EPS_Directory

I am trying to write a simple script that will change my directory in my main shell. I have it working to change directory within the sub-shell (shown above), but obviously when the script is done running it kicks me back out to the outer shell and I am back in my original directory.

Is it possible to pass a command to the outer shell, from within a sub-shell? Can I pass a cd command to the outer shell?

For example if I run:

./cd.sh 2001

I would like my directory to be:

/apps/epsadmin_900002001/EPS

Once I return to the outer shell.

that other guy
  • 101,688
  • 11
  • 135
  • 166
  • Every *process* (subshell, running script) has its **own** *current directory*. See also: [Why cd doesn't work in a bash shell script](http://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script) – Henk Langeveld Apr 13 '14 at 10:06

2 Answers2

2

No, this is not possible.

Instead, you can make a function:

mycd() {
  if [ $# -ne 1 ]; then
    echo "[*]\t Please see usage..."
    echo "[*]\t Usage: $0 <store_number>"
    return 1
  fi

  if [ -z "$1" ]; then
    echo "[*]\t Please see usage..."
    echo "[*]\t Usage: $0 <store_number>"
    return 1
  fi

  Store_Number=$1
  EPS_Directory="/apps/epsadmin_90000$Store_Number/EPS"

  cd "$EPS_Directory"
}

... and store it in a file of its own and source it:

. $HOME/.fun/mycd.sh

Shell functions run in the main process, unlike scripts which run in subprocesses.

Henk Langeveld
  • 7,094
  • 38
  • 53
that other guy
  • 101,688
  • 11
  • 135
  • 166
0

Thanks for all your help! This is my solution.

#   create dj file in /users/(YOUR_NUID) directory
#   paste the dj function into this file.   (vi dj)  (hit i to enter edit mode) (right click to paste)  (hit esc)  (type :wq)
#   source the dj file containing dj() functon by adding this to .profile:
#   . $HOME/dj
#   reload .profile by typing . ./.profile

#   then to run the function simply type dj <storenumber> to jump between EPS directory folders.


dj(){

Store_Number=$1
EPS_Directory="/apps/epsadmin_90000"$Store_Number"/EPS"

    if [ -e $(echo $EPS_Directory) ]; then
        cd $EPS_Directory
        echo "You are now in directory: $EPS_Directory"
    else
        echo "Directory $EPS_Directory does not exist."
    fi 

}