Exercise

Passing Data to a Script Exercise

Task

Build a second script from scratch, then feed it data three different ways: an argument, typed input, and a file.

Host
servera
Script
/home/student/scripts/shift_report.sh
  1. Create a new script and make it executable

    Same three steps as the last script: hashbang, content, chmod. You will do this in every scripting exercise from here on.

    cd ~/scripts
    vim shift_report.sh
    #!/bin/bash
    echo "Shift report filed"
    chmod a+x shift_report.sh
    ./shift_report.sh
  2. Take the technician name as an argument

    $1 holds the first argument given on the command line.

    vim shift_report.sh
    echo "Shift report filed by $1"

    Run it without an argument first. $1 is empty and the sentence reads badly, which is worth seeing once. Then run it with a name.

    ./shift_report.sh
    ./shift_report.sh "Jon Luc Picard"
  3. Read the starship name from standard input

    read takes a line from stdin and stores it in a variable.

    vim shift_report.sh
    echo "Which starship did you command?"
    read -r system_name
    echo "The $system_name"

    Run it and type USS Enterprise when it asks.

    cat shift_report.sh
    ./shift_report.sh "Jon Luc Picard"
  4. Supply that input from a file

    The script cannot tell the difference. It just reads a line from stdin, wherever stdin happens to come from.

    echo "USS Enterprise" > worked_system.txt
    cat worked_system.txt
    ./shift_report.sh "Jon Luc Picard" < worked_system.txt
  5. Add a value produced by another command

    $( ) runs the command inside it first, then substitutes its output.

    vim shift_report.sh
    log_file=$(basename /var/log/audit/audit.log)
    echo "Recorded in $log_file"
    ./shift_report.sh "Jon Luc Picard" < worked_system.txt

    Clean up

    rm -f shift_report.sh worked_system.txt
    cd ~