Scripting Imp rules
1. Command Substitution:
old style: `command`
new style: $(command) -> Recommanded
Eg: echo "Todays date is: `date +%D`"
echo "Todays date is:$(date +%D)"
2. variable substitution
$variable name
${variablename} -> Recommanded
ouput: $NAME
3.Arihmetic operations:
We can perform arthemetic operations using 4 ways:
2 nd method is not used mostly
6. Terinary operator(The name I used to call)
From my experience I use the && and || to reduce an if statement to a single line.
Say we are looking for a file called /root/Sample.txt then the traditional iteration would be as follows in shell:
if [ -f /root/Sample.txt ]
then
echo "file found"
else
echo "file not found"
fi
These 6 lines can be reduced to a single line:
[[ -f /root/Sample.txt ]] && echo "file found" || echo "file not found"
When running a few iterations to set variables or to create files etc., life is easier and the script looks slicker using the single line if function, it's only drawback is that it becomes a bit more difficult to implement multiple commands from a single iteration however you can make use of functions.
7. File Test options:
Different methods to perform incremental operation in bash
Here there is a consolidated list of methods which you can choose based on your shell and environment to increment a variable. In the above script where I have used ((failed++)) or LINE=$(($LINE+1)), just replace this with any of the methods from the below table.
| Number | Incremental Variable |
|---|---|
| 1 | var=$((var+1)) |
| 2 | var=$((var++)) |
| 3 | ((var=var+1)) |
| 4 | ((var+=1)) |
| 5 | ((var++)) |
| 6 | ((++var)) |
| 7 | let "var=var+1" |
| 8 | let "var+=1" |
| 9 | let "var++" |
| 10 | let var=var+1 |
| 11 | let var+=1 |
| 12 | let var++ |
| 13 | declare -var var; var=var+1 |
| 14 | declare -var var; var+=1 |
| 15 | var=$(expr $var + 1) |
| 16 | var=`expr $var + 1` |
Comments
Post a Comment