Skip to main content

0110 | Scripting

Scripting

Bash Scripting | Basics

  • shebang | #!
  • specify the shell after the shebang | #!/bin/bash
  • example | hello-world
    #!/bin/bash

    # This is a comment
    echo "Hello world"
  • running scripts
    • bash hello-world.sh
      • here the bash program is the executable program
    • or by making the script executable
      • chmod +x hello-world.sh --> ./hello-word.sh
  • example | executing commands example
    #!/bin/bash

    user=$(whoami)
    hostname=$(hostname)
    directory=$(pwd)
    # display info
    echo "User=[$user] Host=[$hostname] Working dir=[$directory]"
    echo "Contents:"
    ls

Bash Scripting | Control Structures

  • if | -d (dirs) | -e (files)
  • example | if-examples.sh
    #!/bin/bash

    if [[ -d /etc/ ]]; then
    echo /etc/ is indeed a directory
    fi

    # check to see if a file exists
    if [[ -e sample.txt ]]; then
    echo the file sample.txt exists
    else
    echo the file sample.txt does NOT exist
    fi

    TEST_VAR="test"
    if [[ $TEST_VAR == "test" ]]; then
    echo TEST_VAR has a value of "test"
    elif [[ $TEST_VAR == "again" ]]; then
    echo TEST_VAR has a value of "again"
    else
    echo TEST_VAR has an unknown value
    fi
  • numerical values | -ne | -eq | -gt | -ge | -lt | -le
  • string values | == | != | < | >
  • example | comparison-examples.sh
    #!/bin/bash

    # create variables
    x=1
    echo x=["$x"]
    y=2
    echo y=["$y"]
    z=2
    echo z=["$z"]

    # numeric -- not equals
    if [[ "$x" -ne "$y" ]]; then
    echo ["$x"] ne ["$y"]
    fi

    # numeric -- equals
    if [[ "$y" -eq "$z" ]]; then
    echo ["$y"] eq ["$z"]
    fi

    # numeric -- greater than
    if [[ "$y" -gt "$x" ]]; then
    echo ["$y"] gt ["$x"]
    fi

    # numeric -- greater than or equal to
    if [[ "$y" -ge "$z" ]]; then
    echo ["$y"] ge ["$z"]
    fi

    # numeric -- less than
    if [[ "$x" -lt "$y" ]]; then
    echo ["$x"] lt ["$y"]
    fi

    # numeric -- less than or equal to
    if [[ "$y" -le "$z" ]]; then
    echo ["$y"] le ["$z"]
    fi

    # ***************** string comparison ********************
    a="A"
    echo a=["$a"]
    b="B"
    echo b=["$b"]
    anotherA="A"
    echo anotherA=["$anotherA"]

    # string -- equals
    if [[ "$a" == "$anotherA" ]]; then
    echo ["$a"] "==" ["$anotherA"]
    fi
    # string -- not equals
    if [[ "$a" != "$b" ]]; then
    echo ["$a"] "!=" ["$b"]
    fi
    # string -- less than
    if [[ "$a" < "$b" ]]; then
    echo ["$a"] "<" ["$b"]
    fi
    # string -- greater than
    if [[ "$b" > "$a" ]]; then
    echo ["$b"] ">" ["$a"]
    fi
  • example | case-example.sh
    #!/bin/bash

    # switch off of the first command line argument
    case $1 in
    [1-3])
    message="Argument is between 1 and 3 inclusive"
    ;;
    [4-6])
    message="between 4 and 6 incl"

    ;;
    [7-9])
    message="between 7 and 9 inc"
    ;;
    1[0-9])
    message="between 10 and 19 inc"
    ;;
    *)
    message="I don't understand the argument or it is missing"
    ;;
    esac

    # print msg
    echo $message

Bash Scripting | Loops

  • Definite loops
    • know the number of loops before it starts
    • most common: for loop
  • Indefinite Loops
    • do NOT know the number of loops until the end
    • most common: while loop
  • Indefinite loop != Infinite loop
  • example | loop-examples.sh
    #!/bin/bash

    echo ---------------------------------------
    echo For loops

    echo Print out a hard-coded sequence
    for i in 1 2 3 4 5; do
    echo Index=[$i]
    done

    echo Print out a generated sequence
    for i in {1..5}; do
    echo Index=[$i]
    done


    echo Print out a generated sequence using a 3-expression format
    # Note: Double parenthesis are used since we are
    # doing arithmetic
    for(( i=1; i<=5; i++))
    do
    echo Index=[$i]
    done

    echo Print out the last line of each shell script
    for FILE in *.sh
    do
    echo ===================================
    echo File=[$FILE]
    tail -n 1 $FILE
    done
    echo ''

    #******* while loop ********************
    echo ----------------------------
    echo While loop

    echo Executing a while loop to countdown to blastoff
    counter=5
    while [[ $counter -gt 0 ]]; do
    echo Countdown [$counter]
    counter=$(($counter - 1))
    done
    echo Blastoff

Bash Scripting | Examples

  • command line arguments

    • $0 | the name of the script
    • $# | argument count
    • $@ | argument list
      • iterate-able
      • $0 is not included
    • $* | argument string
      • all of the args in 1 string
    • arg 12 is ${12}
      • NOT $12 (=$1 and "2")
  • example | command-line-arguments-example.sh

    #!/bin/bash

    # Processing command line arguments

    echo Name of script [$0]
    echo Command line argument count [$#]

    # iterate through each argument
    for arg in $@; do
    echo Argument [$arg]
    done

    echo All arguments [$*]

    # use parenthesis for arguments with numbers 10 or larger
    if [ "${12}" != "" ]; then
    echo Argument 12 is [${12}]
    echo Argument 12 is NOT [$12]
    fi
  • example | generate-password.sh | !not working!

    #!/bin/bash

    # Grab the command line arguments
    passwd_word_count=$1
    separator=$2

    # Start with a blank password
    password=''

    # Get the total number of words in the word list
    total_word_count=`wc -l ../wordlist.txt | awk '{print $1;}'`

    # Build the password using the specified number of words
    for (( i=1; i<=$passwd_word_count; i++ ))
    do
    # Generate a random number using OpenSSL to by cryptographically secure
    rand_num_hex=`openssl rand -hex 4`
    rand_num_dec=$((16#$rand_num_hex))

    # Use the random number as an index into the word list
    word_index=$(($rand_num_dec % $total_word_count))
    random_word=`awk -v idx="$word_index" '{if (NR==idx) print $1}'`

    # Capitalize the word
    random_word_upper=`echo ${random_word^}`

    # Insert a separator if this isn't the first word in the passwod
    if [[ ${password} -gt 0 ]]; then
    password=$password$separator$random_word_upper
    else
    password=$random_word_upper
    fi
    done

    echo $password
    • running it | ./generate-password.sh 4 '-'