437 bash control-flow
我怎样才能在 bash 中做这样的事情?
if "`command` returns any error";
then
echo "Returned an error"
else
echo "Proceed..."
fi
Run Code Online (Sandbox Code Playgroud)
Kei*_*son 535
如果命令成功或失败,如何有条件地做某事
这正是 bash 的if声明所做的:
if command ; then
echo "Command succeeded"
else
echo "Command failed"
fi
Run Code Online (Sandbox Code Playgroud)
从留言中加入信息:您没有需要使用[...]语法,在这种情况下。[本身就是一个命令,非常接近于test. 它可能是在 an 中最常用的命令if,这可能会导致假设它是 shell 语法的一部分。但是如果你想测试一个命令是否成功,直接使用命令本身和if,如上所示。
Bru*_*ger 197
对于您希望在 shell 命令有效时发生的小事情,您可以使用以下&&构造:
rm -rf somedir && trace_output "Removed the directory"
Run Code Online (Sandbox Code Playgroud)
同样,对于您希望在 shell 命令失败时发生的小事情,您可以使用||:
rm -rf somedir || exit_on_error "Failed to remove the directory"
Run Code Online (Sandbox Code Playgroud)
或两者
rm -rf somedir && trace_output "Removed the directory" || exit_on_error "Failed to remove the directory"
Run Code Online (Sandbox Code Playgroud)
对这些结构做太多事情可能是不明智的,但它们有时可以使控制流更加清晰。
小智 167
检查 的值$?,其中包含执行最近的命令/函数的结果:
#!/bin/bash
echo "this will work"
RESULT=$?
if [ $RESULT -eq 0 ]; then
echo success
else
echo failed
fi
if [ $RESULT == 0 ]; then
echo success 2
else
echo failed 2
fi
Run Code Online (Sandbox Code Playgroud)
小智 70
这对我有用:
command && echo "OK" || echo "NOK"
Run Code Online (Sandbox Code Playgroud)
如果command成功,则echo "OK"执行,因为它成功,执行在那里停止。否则,&&跳过并echo "NOK"执行。
应该注意的是,if...then...fi和&&/||类型的方法处理我们要测试的命令返回的退出状态(成功时为 0);但是,如果命令失败或无法处理输入,某些命令不会返回非零退出状态。这意味着通常的if和&&/||方法不适用于这些特定命令。
例如,在 Linux 上file,如果GNU接收到一个不存在的文件作为参数并且find找不到用户指定的文件,它仍然会以 0 退出。
$ find . -name "not_existing_file"
$ echo $?
0
$ file ./not_existing_file
./not_existing_file: cannot open `./not_existing_file' (No such file or directory)
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们可以处理这种情况的一种潜在方法是读取stderr/stdin消息,例如那些由file命令返回的消息,或者像 in 解析命令的输出find。为此,case可以使用语句。
$ file ./doesntexist | while IFS= read -r output; do
> case "$output" in
> *"No such file or directory"*) printf "%s\n" "This will show up if failed";;
> *) printf "%s\n" "This will show up if succeeded" ;;
> esac
> done
This will show up if failed
$ find . -name "doesn'texist" | if ! read IFS= out; then echo "File not found"; fi
File not found
Run Code Online (Sandbox Code Playgroud)