Shell Scripting - Part 2

From CDOT Wiki
Jump to: navigation, search

Online Scripting Resources

If you require additional practice in creating shell scripts using logic, loops and mathematical operations, run the commands in your Matrix account:
  • /home/murray.saul/scripting-2
  • /home/murray.saul/scripting-3


Lab 2 Scripting Content

Bash Shell Scripting Tips

  • Data Input:

    A shell script can obtain data from a number of methods: reading input files, using arguments when issuing command (positional parameters), or prompting for data to store in a variable. The later method can be accomplished by using the read command, for example: read -p "Enter your name: " userName.

  • Mathematical Expressions:

    In shell scripting, data is stored in variable as text, not other data types (ints, floats, chars, etc) like in compiled programs like C or Java. In order to have a shell script perform mathematical operations, number or variable need to be surrounded by two sets of parenthesis ((..)) in order to convert a number stored as text to a binary number.

    Examples

    var1=5;var2=10
    echo "$var1 + $var2 = $((var1+var2))"

    Note: shell does not perform floating point calculations (like 5/10). Instead, other commands like awk or bc would be required for floating point calculations (decimals)

  • Loops (iteration):

    Loops and logic are a very important elements of shell scripting (not to mention programming as well). Determinant loops (such as for loops) usually repeat for a preset number of times (eg. counts, positional parameters stored). In-determinant loops (such as while or until loops) may repeat based on unknown conditions (like waiting for user to enter correct data). Test conditions can be used with in-determinant loops, or even commands! If a command runs successfully (eg ls, cd, grep matching a pattern), zero (true) value is returned, otherwise a non-zero (false) value is returned. Command options or redirection to /dev/null can be used to just test if command runs, but not display stdout or stderr. Conditional statements "and" (&&) / "or" (||) can also be used when testing multiple conditions.

    Examples (try in a shell script)

    set ops235 is fun
    for x
    do
     echo "argument is $x"
    done

    for x in $(ls)
    do
     echo "Filename: $x"
    done

    read -p "enter a whole number: " num
    until echo $num | grep -q "^[0-9][0-9]*$"
    do
     read -p "Incorrect. Please enter WHOLE NUMBER: " num
    done

    read -p "pick a number between 1 and 10: " num
    while [ $num -lt 1 ] || [ $num -gt 10 ]
    do
     
    read -p "Incorrect. Please pick number between 1 and 10: " num
    done