I don't really see why you can't just do
dir='/home/Documents/projectDirectory'
if ! mkdir "$dir"; then
printf 'Something went wrong when trying to create "%s"\n' "$dir" >&2
exit 1
fi
printf '"%s" created, now doing other things...\n' "$dir"
The call to mkdir
will fail if $dir
already exists.
If you need to allow for the directory to exist and only bail out if mkdir
fails to create it, then add -p
to the mkdir
call above, or do an explicit test for the existence of the directory:
dir='/home/Documents/projectDirectory'
if [ ! -d "$dir" ]; then
if ! mkdir "$dir"; then
printf 'Something went wrong when trying to create "%s"\n' "$dir" >&2
exit 1
fi
printf '"%s" created\n' "$dir"
fi
echo 'now doing other things...'
I'm using the -d
test here to test whether $dir
may be a directory. I do this because I assume that the rest of the script will require that the name doesn't just exists but that it refers to an actual directory.
Don't try to store commands in variables, it's rarely if ever what you need to do. It's not a good way to save on typing things out. If you need a shorter way of performing an action in a shell script, create a shell function for it.
Also, get into the habit of always double-quoting your variable expansions. That way your shell scripts will always correctly handle filenames with spaces in them and will never accidentally invoke filename globbing.
Related:
Other things:
CREATE_DIRECTORY=mkdir $FILEPATH
This will run $FILEPATH
as a command with CREATE_DIRECTORY=mkdir
in its environment. It will fail because $FILEPATH
is a directory (if it exists) or at least not a command.
To create a variable with spaces in its value, quote the value.
The line
if [ -e "${CREATE_COMMAND}" ]; then
will not create a directory. It will test whether the value in $CREATE_COMMAND
corresponds to a name in the file hierarchy.
I don't know what error_exit
is, but it's probably a shorthand for a simple echo
and exit 1
or similar, right?