You can use awk:
awk '$0<1{$0=1}$0>5{$0=5}1' <<<"$var"
If the variable is less than 1, change it to 1. If it is greater than 5, change it to 5. 1
at the end is always true, so awk performs the default action, which is to print the record.
Some additional explanation:
<<<
is an alternative way of writing echo "$var" | awk ...
, supported by bash
$0
refers to the current "record", which in this case is the variable that has been echoed to bash
- awk works like
condition { action }
, so each block is only run if the condition before it is true
- if no
{action}
part is specified, the default action is {print}
, so that's what the 1
at the end does.
For example:
$ var=0.001
$ awk '$0<1{$0=1}$0>5{$0=5}1' <<<"$var"
1
$ var=5.001
$ awk '$0<1{$0=1}$0>5{$0=5}1' <<<"$var"
5
To overwrite the variable, you can use command substitution:
var=$(awk '$0<1{$0=1}$0>5{$0=5}1' <<<"$var")
If you like confusing yourself, you can do the same thing using two ternary operators instead:
awk '{$0=$0<1?1:$0>5?5:$0}1' <<<"$var"
bash
arithmetic doesn't support fractions, only whole numbers.