shell

Saving bash lines

Thanks to the short-circuit behaviour of the && operator, if-statements can be replaced by:

[[ test ]] && if_true_do_this || otherwise_do_that

So, instead of writing:

if [[ "$1" == "$2" ]]; then
echo "$1 equals $2"
else
echo "$1 differs from $2"
fi

One can write:

[[ "$1" == "$2" ]] && echo "$1 equals $2" || echo "$1 differs from $2"

Braces can be used to run more than a single command:

[[ test_condition ]] && { true_stuff_1; true_stuff_2; } || { false_stuff_1; false_stuff_2; }

Via | commandlinefu

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields