Shell variable issue when trying to mkdir

36,003

Solution 1

The quotes prevent the expansion of ~.

Use:

CLIENT_BUILD_DIR=~/Desktop/TempDir/

if [ ! -d "$CLIENT_BUILD_DIR" ]
then mkdir "$CLIENT_BUILD_DIR"
fi

Solution 2

The ~ character is not reinterpret when used in a variable.

You can use CLIENT_BUILD_DIR="$HOME/Desktop/TempDir/" instead.

Solution 3

mkdir ${CLIENT_BUILD_DIR} will do. No directory will be created if it already exists.

Share:
36,003
hax0r_n_code
Author by

hax0r_n_code

I'm just trying to learn..

Updated on November 09, 2020

Comments

  • hax0r_n_code
    hax0r_n_code over 3 years

    Any ideas what is wrong with this code?

    CLIENT_BUILD_DIR="~/Desktop/TempDir/"
    
    if [ ! -d $CLIENT_BUILD_DIR ]
    then
       {
          mkdir $CLIENT_BUILD_DIR
       }
    fi
    

    I get the error: mkdir: ~/Desktop: No such file or directory.

    Obviously the directory is there and the script works if I replace the variable with ~/Desktop/TempDir/

    • Jite
      Jite about 11 years
      One more tip, you can simplify the code to [ -d $CLIENT_BUILD_DIR ] || mkdir $CLIENT_BUILD_DIR and preferably add || echo "Error trying to create dir: $CLIENT_BUILD_DIR" :)
    • anishsane
      anishsane about 4 years
      Why not simply use mkdir -p? You don't have to check if not exist then create.