Linux provides us with some expansions for command, arithmetic, addition and subtraction, comparison, ternary, assignment, and process substitution operations.

Command

We can execute the output as a command by using the $() or `` symbols.

Let’s use the $() symbols to do this first:

1
2
3
echo "ls -l" > ls_l_command_file
cat ls_l_command_file
$(cat ls_l_command_file)    # This will run the file content "ls -l" as a command.
img

Alternatively, we can use backtick symbols to achieve the same effect:

1
`cat ls_l_command_file`    # This will run the file content "ls -l" as a command.
img

Arithmetic

We can use arithmetic expansion to quickly calculate numerical values.

Some of the operators we can use are:

Operator Meaning
VARIABLE++ VARIABLE‑‑ self increasing or deceasing after the variable is obtained
++VARIABLE ‑‑VARIABLE self increasing or deceasing before the variable is obtained
- + negative or positive number
! ~ logical or bitwise negation
** exponentiation
* / % multiplication, division, remainder
+ - addition, subtraction
<= >= < > less than equals, greater than equals, less than, greater than
== != equal or not equal
expr ? expr : expr ternary operator
= *= /= %= += -= <<= >>= &= ^= assign the operation result to a variable

Addition and Subtraction

1
2
echo $((1+1))    # 2
echo $((1-1))    # 0
img

Prints addition and subtraction results

Comparison

1
2
3
4
5
6
echo $((1<=1))    # true
echo $((1>=1))    # true
echo $((1<1))    # false
echo $((1>1))    # false
echo $((1==1))    # true
echo $((1!=1))    # false
img

Prints comparison results

Ternary Operator

Positive and negative numbers are true, only zero is false

1
2
3
echo $((1?20:-20))    # 20
echo $((0?20:-20))    # -20
echo $((-1?20:-20))    # 20
img

Prints true or false of the ternary operation result

Assignment Operator

1
2
3
4
NUM=2
echo $((NUM*=NUM))    # 4
echo $((NUM*=2))    # 8
echo $((NUM*=4))    # 32
img

Prints assignment operation results

Process Substitution

We can use the <() symbols to use the result of the command output as a file:

1
2
cat <(ls)    # sequentially prints the listed files
tac <(ls)    # sequentially prints the listed files in reversed order
img

Treat ls results as a file and print it with cat and tac commands

References 3.5.4 Command Substitution, 3.5.5 Arithmetic Expansion, 6.5 Shell Arithmetic, 3.5.6 Process Substitution

Buy me a coffeeBuy me a coffee