我希望在一行if/else条件中有以下的等价项。
$maxline=`cat journald.conf | grep "#SystemMaxUse="`
if [ $maxline == "#SystemMaxUse=" ]
then
sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2
mv journald.conf2 journald.conf;
else
echo "This file has been edited. You'll need to do it manually."
fi
我试图把它放到一个单行命令中。到目前为止,我已经得到了除了命令的其他部分之外的所有内容。下面是我目前得到的内容...
maxline=`cat journald.conf | grep "#SystemMaxUse="` && if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; fi
那么我如何将上面代码的else部分包含到我的命令中呢?提前感谢您的帮助。
5条答案
按热度按时间olhwl3o21#
看起来你的思路是对的,你只需要在“;“然后”语句。而且我会用分号将第一行和第二行分开,而不是用“&&"将其连接起来。
同样在你的原始脚本中,当声明maxline时,你使用了反勾号“′”而不是单引号“'”,这可能会导致问题。
gg58donl2#
总结其他答案,供一般用途:
多行 if... then 陈述式
单行版本
if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi
使用OR运算符
( foo && a && b ) || ( bar && c && d ) || e && f;
备注
请记住,AND和OR运算符评估前一个操作的结果代码是否等于true/success(
0
)。因此,如果自定义函数返回其他值(或根本不返回任何值),您可能会遇到简化AND/OR的问题。在这种情况下,您可能需要将( a && b )
之类的值替换为( [ a == 'EXPECTEDRESULT' ] && b )
等。另请注意,
(
和[
是技术上的命令,因此需要在它们周围使用空格。除了
then a && b; else
这样的一组&&
语句之外,你还可以在then $( a; b ); else
这样的子shell中运行语句,尽管这样做效率较低。同样的道理也适用于result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ]
这样的语句,而不是( foo && a && b ) || ( bar && c && d )
。尽管这样你会得到更多不那么紧凑的多行语句。epggiuax3#
这不是问题的直接答案,但您可以使用OR运算符
56lgkhnf4#
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
extends
I found the interested thing on the book "Advanced Bash-Scripting Guide"
q3qa4bjr5#
我正在构建一个脚本,以查看我的多行shell脚本是否有效,因为我需要验证Linux目录是否存在于我的情况中。
如果希望在单行上创建相同类型的脚本或条件,则必须遵守此语法结构。