是否可以从条件内的命令输出中设置变量,如果没有为变量赋值,则条件为false。
如果我将变量设置为不返回的grep,然后进行测试:
test=$(echo hello | grep 'helo')
if [[ ! -z $test ]]; then
echo "is set"
else
echo "not set"
fi输出:未设置(这是预期的)
但我试着把这一切都归结为这样一句话:
test=
if [[ ! -z test=$(echo hello | grep 'helo') ]]; then
echo "is set"
else
echo "not set"
fi输出:"is set“(预期未设置)
发布于 2018-02-23 04:43:49
如果有匹配,grep将返回success,因此您可以这样做:
if test=$(echo hello | grep 'helo')
then
echo "Match: $test"
else
echo "No match"
fi如果您正在运行退出代码无法区分的内容,则可以在同一行上分配和签入两个语句:
if var=$(cat) && [[ -n $var ]]
then
echo "You successfully piped in some data."
else
echo "Error or eof without data on stdin."
fi(或者,如果即使命令报告失败也要检查结果,则使用;而不是&& )
发布于 2018-02-23 14:24:26
使用shell的parameter expansion alternate value语法、echo -e和一些退格符:
test=$(echo hello | grep 'helo'); echo -e not${test:+\\b\\b\\bis} set它根据grep找到的内容输出is set或not set。
https://stackoverflow.com/questions/48936439
复制相似问题