1

The following is a snippet of a larger script I'm attempting. I just want this part to recognize the argument is a directory and then cd to that directory: i.e ./larj /etc.

#!/bin/ksh
# Filename: larj.sh

if [ $# -gt 1 ]; then
    echo "0 or 1 arguments allowed."
    exit
fi
if [ -f "$1" ]; then
    echo "directory only."
    exit
else
    if [ -d "$1" ]; then
        cd $1
    fi
fi

When I run the script with /etc as the argument, it appears nothing happens; it stays in the same directory with no error. Anyone have any suggestions how to get it to change directories?

Thanks

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
T2true
  • 61
  • 1
  • 6

2 Answers2

1

The cd is taking place within the script's shell.

When the script ends, it's shell exits, and you return to the directory before running the script. In order to change the directory you can

mkdir testdir
. ./your_script.sh testdir

At the end of the script you will be moved at directory testdir.

cateof
  • 6,608
  • 25
  • 79
  • 153
-1

The problem why you cd can't work is that cd executes in the sub-shell when you execute the script as ./larj /etc. So when you execute the script, it changes the working directory of the subshell and has no impact on the current shell.

So you can execute it as . ./larj /etc.

Refer to Why doesn't “cd” work in a bash shell script?.

zhenguoli
  • 2,268
  • 1
  • 14
  • 31
  • Ok. That makes sense - subshell. As I mentioned, this is just a snippet of the larger script. So, the snippet is fine. When I add it to the larger script, it should cd to the directory in the argument, perform its function, and return the results at the shell where I am working? Is that accurate? – T2true Jun 23 '17 at 16:32
  • @T2true. Yes, it works well. You can test by a small bash script which contains only `cd /tmp && mkdir -p test` to check whether the `test` directory exists. Then you will find that it works well. – zhenguoli Jun 24 '17 at 00:54