Some bash programming helpers
how to and expressions if z var e var :
expression1 && expression2 - true if both expression1 and expression2 are true.
if [ ! -z "$var" ] && [ -e "$var" ]; then
echo "'$var' is non-empty and the file exists"
fi
if [[ -n "$var" && -e "$var" ]] ; then
echo "'$var' is non-empty and the file exists"
fi
Subtract two variables in Bash :
count=$(($number1-$number2))
How to check if a string contains a substring in Bash :
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
string='My string';
if [[ $string =~ "My" ]]
then
echo "It's there!"
fi
if grep -q foo <<<"$string"; then
echo "It's there"
fi
Compare Numbers in Linux Shell Script :
$num1 -eq $num2 check if 1st number is equal to 2nd number
$num1 -ge $num2 checks if 1st number is greater than or equal to 2nd number
$num1 -gt $num2 checks if 1st number is greater than 2nd number
$num1 -le $num2 checks if 1st number is less than or equal to 2nd number
$num1 -lt $num2 checks if 1st number is less than 2nd number
$num1 -ne $num2 checks if 1st number is not equal to 2nd number
Compare Strings in Linux Shell Script :
$var1 = $var2 checks if var1 is the same as string var2
$var1 != $var2 checks if var1 is not the same as var2
$var1 < $var2 checks if var1 is less than var2
$var1 > $var2 checks if var1 is greater than var2
-n $var1 checks if var1 has a length greater than zero
-z $var1 checks if var1 has a length of zero
File comparison in Linux Shell Script
-d $file checks if the file exists and is it’s a directory
-e $file checks if the file exists on system
-w $file checks if the file exists on system and if it is writable
-r $file checks if the file exists on system and it is readable
-s $file checks if the file exists on system and it is not empty
-f $file checks if the file exists on system and it is a file
-O $file checks if the file exists on system and if it’s is owned by the current user
-G $file checks if the file exists and the default group is the same as the current user
-x $file checks if the file exists on system and is executable
$fileA -nt $fileB checks if file A is newer than file B
$fileA -ot $fileB checks if file A is older than file B
2020-10-16 13:22:18
Comments
Add a Comment