bash 脚本中的 mkdir 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2743673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:14:50  来源:igfitidea点击:

mkdir error in bash script

bashshellmkdir

提问by Dónal

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

以下是我在 Windows 上的 cygwin 下运行的 bash 脚本的片段:

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:58on the command-line it succeeds, why does the same command not work in the script?

但是,如果我/cygdrive/c/Temp/deploy/2010-04-30_11:47:58在命令行上输入它成功,为什么相同的命令在脚本中不起作用?

Thanks, Don

谢谢,唐

回答by Bert F

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 mkdircommand, 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 ("").

像大多数 Unix shell(甚至可能是所有 shell)一样,Bourne (Again) Shell (sh/bash) 区分大小写。dir var 在deployDir任何地方都被调用(混合大小写),除了mkdir命令,在那里它被调用deploydir(全部小写)。由于deploydir(全小写)被认为是与deployDir(混合大小写)不同的变量,并且deplydir(全小写)从未分配过值,因此deploydir(全小写)的值是空字符串(“”)。

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

没有引号 ( mkdir $deploydir),该行实际上变为mkdir(只是没有所需操作数的命令),因此错误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'.

使用引号 ( mkdir "$deploydir"),该行有效地变为mkdir ""(使用空字符串的非法目录名称创建目录的命令),因此错误mkdir: cannot create directory'.

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

如果mkdir "$deployDir"目标目录名称包含空格,建议使用带引号 ( )的形式。

回答by Paul R

Change:

改变:

mkdir -p $deploydir

to

mkdir -p "$deploydir"

回答by unwind

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

出于显而易见的原因,Windows 上的文件名中不能有冒号。