Shell Script Examples: case, count, for, if, while and User input

If you, like so many other people these days, switch to Linux you will come in contact with something called unux scripts, shell scripts or bash scripts. These scripts are text-files that execute commands just like bat-files in Windows. I prefer shell-scripts because i think they are more powerful then bat-files but that is just my opinion.

Some things you should know:
#!/bin/bash usually is the first line in a bash script. It is called shebang (also called a hashbang, hashpling, or pound bang) and specifies in which shell to execute the code that follows below.

Everything after a # is a comment and does not get executed.

Below you will find examples of a few things that you can do with shell scripts on Linux and other Unixes. If you have questions: have a look at the man page of the command or post a comment and I will try to explain.






User Input

3 Replies to “Shell Script Examples: case, count, for, if, while and User input”

  1. Hi i would like to know how to write a math script that ask the user for three numbers. gives the user three options to choose from: add,multiply and average. I also would like to use a case statement to make it work, save as one function.


    1. I would use “read” to get user input. Example:
      read USERINPUT
      echo $USERINPUT

      For the math bit there is a nifty utility called expr. Example:
      expr 12 + 12

      will return the result of 24

      I hope that this helps you

    2. Here is a non complete sample of how you can solve the problem. Please observe that bc is used instead of expr for calculations with decimals. The scale variable tells bc how many decimals to use when computing the numbers.

      echo -n “First number: ”
      read N1

      echo -n “Second number: ”
      read N2

      echo -n “Third number: ”
      read N3

      echo ”
      A Add
      M Multiply
      V Average

      echo -n “Please choose A, M or V: ”
      read JOB

      case $JOB in
      expr $N1 + $N2 + $N3
      expr $N1 \* $N2 \* $N3
      TOTAL=expr $N1 + $N2 + $N3
      echo “scale=2;$TOTAL / 3 ” | bc -l
      *) echo wrong choice;;

Leave a Reply

Your email address will not be published.