Bash on ubuntu 12.04 (installed using Wubi, could never be easier)
Floating point arithmetic
- Using piping ( | ) basic=$(echo "scale=2; 250.00" | bc)
commission=$(echo "scale=2; 50.00" | bc)
pay=$(echo "scale=2; ${basic}+${commission}" | bc)
echo "Your pay for this week (RM) ${pay}"
Output :
Your pay for this week (RM) 300.00
Info and discussion about using bc (base conversion)
Read user input (Read)
- Method 1 echo "Enter name : "
- Method 2 echo -n "Enter name: "
- Method 3 read -p "Enter name: " name
read name
Output :
Enter name :
Tarzan
read name
Output :
Enter name : Tarzan
Output :
Enter name : Tarzan
If Statement
- Comparisons
- If Else if [ "$option" = "y" ]; then
Numeric Comparison | |
---|---|
-eq | equal |
-ne | not equal |
-gt | greater than |
-ge | greater equal |
-lt | less than |
-le | less equal |
! | negates |
String Comparisons (and other comparisons)
loop=true
else
loop=false
fi
Other examples of if statements
Case Statement
read -p "Enter number(1-4): " codecase "$code" in '1')
echo "One. "
;;
'2')
echo "Two. "
;;
'3')
echo "Three. "
;;
'4') echo "Four. "
;;
esac
echo "Code entered ${code}"
Loop Statement
More on loops : Cyberciti,Other reference links : Free OS, codewiki
Download sample bash file (coming up soon)
Starting with bash
Download Starting with bash.txt- Start up Ubuntu (Im using Ubuntu 12.04)
- Open Terminal
- Go to Desktop (or any other directory) Type "cd Desktop" (without quotes) in terminal and press Enter.
- Create the bash file Type "gedit filename.sh" (without quotes) in terminal and press Enter. Where filename is the name of the bash file name.
- Make the bash file executable Type in "sudo chmod +x filename.sh" (without quotes) in terminal and press Enter. Or "chmod 4755 filename.sh" (without quotes) and press Enter.
- Run or execute bash program Type in "./filename.sh" (without quotes) in terminal and press Enter.
gedit is a text editor comes with Ubuntu (and other unix OS). Other editors like vim also used, but normally vim doesn't comes pre-installed to the system. Which may require manual installation and super user rights (Sudo).
Type in the program, save the file and close the gedit (text editor). The text editor must be close to allow the terminal to ready to process next command.
Hope this helps.