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
-
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 -
Take the technician name as an argument
$1holds the first argument given on the command line.vim shift_report.shecho "Shift report filed by $1"Run it without an argument first.
$1is 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" -
Read the starship name from standard input
readtakes a line from stdin and stores it in a variable.vim shift_report.shecho "Which starship did you command?" read -r system_name echo "The $system_name"Run it and type
USS Enterprisewhen it asks.cat shift_report.sh ./shift_report.sh "Jon Luc Picard" -
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 -
Add a value produced by another command
$( )runs the command inside it first, then substitutes its output.vim shift_report.shlog_file=$(basename /var/log/audit/audit.log) echo "Recorded in $log_file"./shift_report.sh "Jon Luc Picard" < worked_system.txtClean up
rm -f shift_report.sh worked_system.txt cd ~