If it is, then echo 1, otherwise echo 0. This is the command that I am using but it only works partially (more info below). Note that I need to write the script in one line. Note: The [s] in some_proces[s] is to prevent grep from returning itself.
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
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.
To summarize the other answers, for general use:
if [ foo ]; then
a; b
elif [ bar ]; then
c; d
else
e; f
fi
if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi
( foo && a && b ) || ( bar && c && d ) || e && f;
Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0
). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b )
with ( [ a == 'EXPECTEDRESULT' ] && b )
, etc.
Also note that (
and [
are technically commands, so whitespace is required around them.
Instead of a group of &&
statements like then a && b; else
, you could also run statements in a subshell like then $( a; b ); else
, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ]
instead of ( foo && a && b ) || ( bar && c && d )
. Though at that point you'd be getting more into less-compact, multi-line stuff anyway.
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
if [ "$var1" -lt 98 ]; then
var0=9
else
var0=21
fi
extends
condition?result-if-true:result-if-false
I found the interested thing on the book "Advanced Bash-Scripting Guide"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With