Linux:Bash:mkdir 返回什么

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

Linux: Bash: what does mkdir return

linuxbashmkdir

提问by Tu Hoang

I want to write a simple check upon running mkdir to create a dir. First it will check whether the dir already exists, if it does, it will just skip. If the dir doesn't exist, it will run mkdir, if mkdir fails (meaning the script could not create the dir because it does not have sufficient privileges), it will terminate.

我想在运行 mkdir 以创建目录时编写一个简单的检查。首先它会检查目录是否已经存在,如果存在,它将跳过。如果目录不存在,它将运行 mkdir,如果 mkdir 失败(意味着脚本无法创建目录,因为它没有足够的权限),它将终止。

This is what I wrote:

这是我写的:

if [ ! -d "$FINALPATH" ]; then
    if [[ `mkdir -p "$FINALPATH"` -ne 0 ]]; then
        echo "\nCannot create folder at $FOLDERPATH. Dying ..."
        exit 1
    fi
fi

However, the 2nd if doesn't seem to be working right (I am catching 0 as return value for a successful mkdir). So how to correctly write the 2nd if? and what does mkdir returns upon success as well as failure?

但是,第二个 if 似乎无法正常工作(我正在捕获 0 作为成功 mkdir 的返回值)。那么如何正确写出第二个if呢?mkdir 在成功和失败时返回什么?

采纳答案by Owen

The result of running

运行的结果

`mkdir -p "$FINALPATH"`

isn't the return code, but the output from the program. $?the return code. So you could do

不是返回码,而是程序的输出。$?返回码。所以你可以这样做

if mkdir -p "$FINALPATH" ; then
    # success
else
    echo Failure
fi

or

或者

mkdir -p "$FINALPATH"
if [ $? -ne 0 ] ; then
    echo Failure
fi

回答by sehe

The shorter way would be

更短的方法是

 mkdir -p "$FINALPATH" || echo failure

also idiomatic:

也是惯用语:

 if mkdir -p "$FINALPATH"
 then
      # .....
 fi

Likewise you can while .....; do ....; doneor until ......; do ......; done

同样你可以while .....; do ....; doneuntil ......; do ......; done

回答by Dr Beco

Just for completeness, you can exit by issuing:

为了完整起见,您可以通过发出以下命令退出:

mkdir -p "$FINALPATH" || { echo "Failure, aborting..." ; exit 1 ; }

Braces are necessary, or else exit 1would execute in both cases.

大括号是必要的,否则exit 1在这两种情况下都会执行。

Or you can create an abort function like:

或者您可以创建一个中止函数,例如:

errormsg()
{
    echo ""
    echo Aborting...
    { exit 1 ; }
}

And then just call it by issuing:

然后只需通过发出以下命令来调用它:

mkdir -p "$FINALPATH" || errormsg "Failure creating $FINALPATH"

Edited:

编辑:

  • Braces, not parenthesis, as parenthesis only exit the subshell. ( Thanks @Charles Duffy )
  • A function to write a message and exit
  • 大括号,而不是括号,因为括号只退出子外壳。(感谢@Charles Duffy)
  • 一个写消息并退出的函数