Skip to content

Code and write bash scripts

by aizzet on September 19th, 2016

This article is just a draft for the moment. Thought you can find some interesting tips…

• Always begin your script with the instruction that telles the shell what program to interpret the script with, when executed. It is called the Shebang. I personally always use:
#!/bin/bash
In this example, the script is to be interpreted and run by the bash shell.

Some other example shebangs are:
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby
#!/bin/ksh #!/bin/awk #!/bin/expect

 

• Shell loop using non-integer variable:
RangeNumber=$(awk 'BEGIN{for(j=0;j<=18;j+=2)print j/100}') #####
for Number in $RangeNumber 0.07 #### you can add another number such as 0.07 here
do
printf -v Number "%1.2f" $Number # in order to impose the format with 2 digits like in 0.10 (N.B. adding \n would go to next line)
echo $Number
done
end
exit 0

 

• Mathematics and operation in the shell:
Example you have:
Angle=0.195
then
iPreviousAngle=`echo "($Angle*1000+5)/1000" | bc -l`
printf -v iPreviousAngle "%1.3f" $iPreviousAngle # in order to impose the format with 2 digits like in 0.10 (N.B. adding \n would go to next line)
echo "Angle=$Angle"
echo "PreviousAngle=$iPreviousAngle"

and therefore
echo $iPreviousAngle
gives
PreviousAngle=.20000000000000000000


• To properly format the variable:
printf -v iPreviousAngle "%1.3f" $iPreviousAngle # in order to impose the format with 2 digits like in 0.10 (N.B. adding \n would go to next line)
echo "PreviousAngle=$iPreviousAngle"

PreviousAngle=0.200

From → Code, commandes shell

No comments yet

Leave a Reply

You must be logged in to post a comment.