Bash:如何测试 mkdir 命令是否失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16633066/
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
Bash: How to test for failure of mkdir command?
提问by Edward
I'm writing a bash script and want to do robust error checking in it.
我正在编写一个 bash 脚本并希望在其中进行强大的错误检查。
The exit status code for mvto make it fail is easy to simulate a failure. All you have to do is move a file that doesn't exist, and it fails.
mv使其失败的退出状态代码很容易模拟失败。你所要做的就是移动一个不存在的文件,它会失败。
However with mkdirI want to simulate it failing. mkdir could fail for any number of reasons, problems with the disk, or lack of permissions, but not sure how to simulate a failure.
但是mkdir我想模拟它失败。mkdir 可能会由于多种原因、磁盘问题或权限不足而失败,但不确定如何模拟失败。
采纳答案by parkydr
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.)
如果目录已经存在,mkdir 将失败(除非您使用 -p),并返回错误代码1(在我的系统上),因此首先创建目录以在您自己的系统上进行测试。(虽然我认为这是所有 shell 的标准。)
Alternatively, make the parent directory read-only.
或者,将父目录设为只读。
回答by Uroc327
Just use
只需使用
mkdir your_directory/
if [ $? -ne 0 ] ; then
echo "fatal"
else
echo "success"
fi
where $?stands for the exit code from the last command executed.
where$?代表执行的最后一个命令的退出代码。
To create parent directories, when these don't exist, run mkdir -p parent_directory/your_directory/
要创建父目录,当这些不存在时,运行 mkdir -p parent_directory/your_directory/
回答by Adrian Frühwirth
if ! mkdir your_directory 2>/dev/null; then
print_error
exit
fi
or
或者
mkdir your_directory 2>/dev/null || { print_error; exit; }
回答by nitin
in your script , you could also put a check for the new dir ....
在您的脚本中,您还可以检查新目录....
mkdir -p new_dir ;
if [ -d new_dir ]
cd new_dir && ...... anything else you want .
else
echo "error in directory creation ";
exit 2 ;
fi
回答by mogul
If you are lazy a simple set -ein the beginning of you script is enough. Often you just want to print an error and then terminate if something goes wrong.
如果你很懒惰,一个简单set -e的脚本开头就足够了。通常,您只想打印错误,然后在出现问题时终止。
Not exactly what you asked for, but perhaps what you want.
不完全是你要求的,但也许是你想要的。

