Graduate Program KB

Shell Scripts

  • Text file that contains commands that can be executed in the unix shell.
  • Can be used for automating repetitive tasks to simplify workflow and perform tasks more efficiently.

Example Bash Script using bash (You can use other shells like zsh,ksh,etc)

    #!/bin/bash

    echo "This will output to the terminal screen"
    varName = "This is a global variable"
    local varName = "This is a local variable"
    read -p "This msg is the prompt and will ask for user input"
    #This is a comment
    
    #If Statements (There are spaces between -z and $1)
    if [ -z $1 ]; then
        echo "No arguments 1"
    else
        echo "$1"
    fi

    #Case Statements
    case $1 in
        start)
        echo "First arg is start"
        ;;
        stop)
        echo "First arg is stop"
        ;;
        *)
        echo "Default Case"
        ;;
    esac

    #Loops
    array=("a" "b" "c")
    
    #Prints out each item in array
    for item in ${array[*]}
    do
        echo ${item}
    done

    #Using Variables
    echo "This is how you use ${varName}

    # Functions
    function FuncName() {
        local firstArg = "$1"
        # $1 $2 $3 ... are the args
    }

    FuncName "arg1" "arg2"

    FuncName2() {
        # Do command that outputs to stdout
    }

    # varName will have value of above command
    local varName=$(FuncName2)

    #Arguments
    echo "This is first argument $1"
    echo "This is 2nd argument $2"
  • To run the script. (Need to give execute permissions)
    chmod +x <bashfile.sh>
    ./bashfile.sh
    ./bashfile.sh arg1 arg2 ...
  • You can schedule the scripts to run using cron jobs
    crontab -e 
    * * * * * /path/to/script arg1 arg 2
    #Minutes, hours, days of month, month, days of week
    #https://crontab.guru/ (Translates into human readable)