简体   繁体   中英

How to write this in one line in bash

How to write this in one line WITHOUT creating extra variables AND duplication of "5"?

A=5
B=10
([[ $A == B ]] && echo $A) || echo gt
A=5; B=10; ([[ $A == B ]] && echo $A) || echo gt

You can separate commands by ; ...

But it's rather unnecessary for most situations. By structuring code, one gets more insight in how it works.

echo gt

That is just one line, and it introduces no variable.

By the way - what's the use of that?

You don't need the parentheses around the bash test and and statement:

A=5; B=10; 
[[ $A -lt $B ]] && echo $A || echo "A >= B"

If you're upset about bulk, it's harder to make it more simple using bash. But since you are using bash, you have other programs at your disposal, such as python:

A=5; B=10;
python -c "print $A if $A < $B else 'A >= B'"

Or Perl:

A=5; B=10;
perl -le "print $A < $B ? $A : 'A >= B';"

Regardless of specific language choice, all are performing a similar task. In this specific case, the perl example is the "lightest". But note that Perl and Python may not be the most portable. If portability is an issue and you don't prefer Bash, consider awk:

A=5; B=10;
awk "BEGIN{print $A < $B ? $A : \"A >= B\"}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM