Bash Shell Script (Unix Shell)

Monday, July 15, 2013

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 : "
    read name

    Output :
    Enter name :
    Tarzan

  • Method 2
  • echo -n "Enter name: "
    read name

    Output :
    Enter name : Tarzan

  • Method 3
  • read -p "Enter name: " name

    Output :
    Enter name : Tarzan



If Statement



Case Statement

read -p "Enter number(1-4): " code

case "$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
  1. Start up Ubuntu (Im using Ubuntu 12.04)

  2. Open Terminal

  3. Go to Desktop (or any other directory)
  4. Type "cd Desktop" (without quotes) in terminal and press Enter.

  5. Create the bash file
  6. Type "gedit filename.sh" (without quotes) in terminal and press Enter. Where filename is the name of the bash file name.

    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.

  7. Make the bash file executable
  8. Type in "sudo chmod +x filename.sh" (without quotes) in terminal and press Enter. Or "chmod 4755 filename.sh" (without quotes) and press Enter.

  9. Run or execute bash program
  10. Type in "./filename.sh" (without quotes) in terminal and press Enter.




Hope this helps.

Leave a Reply

Powered by Blogger.