Search code examples
shellcommand-linecd

In shell script, how to change current directory safely with variable?


The following shell script changes current the directory to the desktop.

v=~/Desktop/
cd $v
pwd # desktop

The following script changes the current directory to home directory instead of generating error.

cd $undefined_variable
pwd # home directory
echo $? # 0

I'm afraid that the script will remove important files if I misspelled a variable for new current directory.

Generally, how do you safely change current directory with variable in shell script?


Solution

  • You can set -u to make bash exit with an error each time you expand an undefined variable.