Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mkdir error in bash script

Tags:

bash

shell

mkdir

The following is a fragment of a bash script that I'm running under cygwin on Windows:

deployDir=/cygdrive/c/Temp/deploy

timestamp=`date +%Y-%m-%d_%H:%M:%S`
deployDir=${deployDir}/$timestamp

if [ ! -d "$deployDir" ]; then
    echo "making dir $deployDir"
    mkdir -p $deployDir
fi

This produces output such as:

making dir /cygdrive/c/Temp/deploy/2010-04-30_11:47:58
mkdir: missing operand
Try `mkdir --help' for more information.

However, if I type /cygdrive/c/Temp/deploy/2010-04-30_11:47:58 on the command-line it succeeds, why does the same command not work in the script?

Thanks, Don

like image 562
Dónal Avatar asked Apr 30 '10 09:04

Dónal


People also ask

How do I check my mkdir error?

mkdir will fail if the directory already exists (unless you are using -p), and return an error code of 1 (on my system), so create the directory first to test this on your own system. (Although I would assume that is standard across all shells.) Alternatively, make the parent directory read-only.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you create directory if not exist in bash?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.


3 Answers

Change:

mkdir -p $deploydir

to

mkdir -p "$deployDir"

Like most Unix shells (maybe even all of them), Bourne (Again) Shell (sh/bash) is case-sensitive. The dir var is called deployDir (mixed-case) everywhere except for the mkdir command, where it is called deploydir (all lowercase). Since deploydir (all lowercase) is a considered distinct variable from deployDir (mixed-case) and deplydir (all lowercase) has never had a value assigned to it, the value of deploydir (all lowercase) is empty string ("").

Without the quotes (mkdir $deploydir), the line effectively becomes mkdir (just the command without the required operand), thus the error mkdir: missing operand.

With the quotes (mkdir "$deploydir"), the line effectively becomes mkdir "" (the command to make a directory with the illegal directory name of empty string), thus the error mkdir: cannot create directory'.

Using the form with quotes (mkdir "$deployDir") is recommended in case the target directory name includes spaces.

like image 76
Bert F Avatar answered Oct 12 '22 06:10

Bert F


Change:

mkdir -p $deploydir

to

mkdir -p "$deploydir"
like image 45
Paul R Avatar answered Oct 12 '22 07:10

Paul R


You can't have colons in file names on Windows, for obvious reasons.

like image 35
unwind Avatar answered Oct 12 '22 06:10

unwind