Linux 尝试 mkdir 时的 Shell 变量问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16085094/
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-08-06 22:44:45  来源:igfitidea点击:

Shell variable issue when trying to mkdir

linuxbashshellvariables

提问by hax0r_n_code

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.

我收到错误消息:mkdir: ~/Desktop: No such file or directory。

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

显然目录在那里,如果我用 ~/Desktop/TempDir/ 替换变量,脚本就可以工作

采纳答案by BeniBela

The quotes prevent the expansion of ~.

引号阻止了 ~ 的扩展。

Use:

用:

CLIENT_BUILD_DIR=~/Desktop/TempDir/

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

回答by tomahh

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

所述~在一个变量中使用时字符不重新解释。

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

你可以CLIENT_BUILD_DIR="$HOME/Desktop/TempDir/"改用。

回答by Oscar Montoya

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

mkdir ${CLIENT_BUILD_DIR}会做。如果目录已经存在,则不会创建目录。