如果 bash 命令的输出为空,请执行某些操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45562771/
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
If output of bash command is empty, do something
提问by stackman
Hi I am new to bash so please excuse me if I have a really silly/easy question. I am writing a script which allows the user to change their region (for wireless). What I am wanting to do is put a check in place, so if they type in an incorrect value, it brings up the prompt again to input the region. I want to do this by checking if the output of the command sudo iw reg set $reg
, if it is a correct input, there is no output. But if it is a wrong input, it gives an error message. I tried to do this but im getting an error:
嗨,我是 bash 新手,所以如果我有一个非常愚蠢/简单的问题,请原谅。我正在编写一个脚本,允许用户更改他们的区域(无线)。我想要做的是检查到位,所以如果他们输入了错误的值,它会再次提示输入区域。我想通过检查命令的输出来做到这一点sudo iw reg set $reg
,如果它是正确的输入,则没有输出。但如果输入错误,则会给出错误消息。我试图这样做,但我收到一个错误:
#!/bin/bash
echo "Please set a region: "
read reg
if [(sudo iw reg set $reg) -ne 0]; then
echo "Please set a valid region: "
read reg
else
echo "Setting reg as $reg"
sudo iw reg set $reg
fi
Thanks in advance
提前致谢
回答by Michael Jaros
You can use the -z
test, type help test
in Bash to learn more (test
is the same as the [
command).
您可以使用-z
测试,输入help test
Bash 以了解更多信息(test
与[
命令相同)。
You should only call iw reg set
once, unless it fails.
你应该只调用iw reg set
一次,除非它失败。
echo "Please set a region: "
while true # infinite loop
do
# read in the region:
read reg
# try the command, and catch its output:
output=$( sudo iw reg set "$reg" 2>&1 )
if [ -z "$output" ]
then
# output is empty - success - leave the loop:
break
else
# output is non-empty - continue:
echo "Please set a valid region. "
fi
done
This snippet checks the success condition you gave in your question (empty output), but it should be noted that usually exit codes should be used if possible.
此代码段检查您在问题中给出的成功条件(空输出),但应注意,如果可能,通常应使用退出代码。
Note the 2>&1
operator redirecting stderr to stdout so any output on either file descriptor will be considered a failure.
请注意2>&1
运算符将 stderr 重定向到 stdout,因此任一文件描述符上的任何输出都将被视为失败。
回答by anubhava
You can use read
in a while
loop:
您可以read
在while
循环中使用:
while read -r -p "Please set a valid region: " reg; do
[[ -z "$(sudo iw reg set $reg)" ]] && break
done
help read
gives this:
help read
给出了这个:
-r
do not allow backslashes to escape any characters-p prompt
output the string PROMPT without a trailing newline before attempting to read$(...)
is command substitutionto execute a command and return output-z
returnstrue
when given string argument (output ofiw
command) is empty
-r
不允许反斜杠转义任何字符-p prompt
在尝试读取之前输出没有尾随换行符的字符串 PROMPT$(...)
是执行命令并返回输出的命令替换-z
返回true
时给定的字符串参数(的输出iw
命令)是空的