Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

One line if/else condition in linux shell scripting

I would like to have the equivelant of the following in a one line if/else condition.

$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  

I'm attempting to put this into a one line command. So far I've gotten it all but the else portion of the command. Here's what I have so far...

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

So how can I include the else portion of the above code into my command? Thank you for your help in advance.

question from:https://stackoverflow.com/questions/18179915/one-line-if-else-condition-in-linux-shell-scripting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".

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

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...