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:
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
?single character wildcard
redirect input - stdin
redirect output - stdout

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

numeric comparisons
-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
    # if...then...else example
    # written by Elliott Technologies

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

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

echo example of case
while [ $val = 1 ]
    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) " ;;

0 blogger-disqus:

Post a Comment