I want to create a script on Linux to create some directories if they do not exists. The directories are declared inside the script itself (not being passed from command line):
#!/bin/bash
varBaseDir="/home/user"
# Directories to create
varAppDir="${varBaseDir}/app"
varAppDataDir="${varBaseDir}/appData"
if [[ -d ${varAppDir} ]]
then
echo "app dir exist"
else
echo "app dir does not exist! creating '${dir}' ..."
mkdir -p ${dir}
if test "$?" -eq "0"
then
echo "succeeded."
else
echo "failed to create directory"
fi
fi
As you can see I create one of the directories. Then I would need to repeat the same code again but with a different directory (next time I want the varAppDataDir to be created).
I tried to figure out how to declare a function:
my_function($dir) {
echo $dir
}
my_funciotn("HELLO")
but I get error:
./test.sh: line 27: syntax error near unexpected token `$dir'
./test.sh: line 27: `my_function($dir) {'
So how to do this right?
mkdir -p "$dir" && echo "succeeded" || echo "failed"
. You don't need to test whether the dir exists,mkdir -p
(at least with GNUmkdir
) silently returns success if the dir exists, and creates it if it doesn't. Unless you really need to log that the dir didn't exist when the script was launched, you really don't need all that.