Sunday, 14 April 2013

Shell Scrripts Tips-N-Tricks

The syntax and examples are written for use with bash (Bourne Again Shell) other shells may vary.
All script files must declare a shell on the first line.All the examples provided herein assume the first line is the following:
    #!/bin/bash
Also, you must have execute permissions on the script file you create. You can give yourself execute permissions by typing the following:
    chmod u+x filename

Special Characters
#comments
*wildcard
?single character wildcard
redirect input - stdin
redirect output - stdout

string comparisons
=equal
!=not equal
<is less than
>is greater than
-nis not null
-zis null

numeric comparisons
-eqequal
-gegreater than or equal to
-gtgreater than
-leless than or equal to
-ltless than
-nenot equal

file operators
-d filefile exists and is directory
-e filefile exists
-f filefile exists and is regular
-s filefile exists and is not empty
file permission tests
-r fileyou have read permission
-w fileyou have write permission
-x fileyou have execute permission
-O fileyou have ownership
-G fileyou have group ownership
file comparisons
file1 -nt file2file1 newer than file2
file1 -ot file2file1 older than file2

if then else statement
operators
-aand
-oor
Example:
    #!/bin/bash
    # if...then...else example
    # written by Elliott Technologies

    NUM=0
    if [ $NUM -eq 0 ]; then
      echo true
    else
      echo false
    fi

while and case example:
#!/bin/bash
# written by Elliott Technologies to demonstrate
# a shell script that implements while and case
# statements

echo example of case
val=1
while [ $val = 1 ]
do
    echo -n "continue:"
    read userval
    case $userval in
      Yes|[Yy] )
        # the above matches on Yes, Y, or y
        echo -n "you answered yes " ;;
      No|[Nn] )
        # the above matches on No, N, or n
        echo Stopping since you answered no
        val=0 ;;
      * )
        echo -n "please answer (Yes/No) " ;;
    esac
done

0 blogger-disqus:

Post a Comment