...
Importantly, auto_log reports an error and terminates script execution if no tag string is specified, via exit 255 (we'll see much more on error handling shortly).
The test is made using a bash if/else/fi block, where double brackets ('"[[ ]]") enclose the test, always followed by a semicolon (";"). Here the test is for string equality (see https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html for a complete list of bash comparison operators). Note that there must always be a space after the open brackets, and one before the close brackets.
Code Block | ||
---|---|---|
| ||
# Sets up auto-logging to a log file in the current directory # using the specified logFileTag (arg 1) in the log file name. auto_log() { local logFileTag="$1" if [[ "$logFileTag" != "" ]]; then local logFilePath="./autoLog_${logFileTag}.log" echo_se ".. logging to $logFilePath" exec 1> >(tee "$logFilePath") 2>&1 else echo_se "** ERROR in auto_log: no logFile argument provided" exit 255 fi } |
...
- Starts automatic logging to a log file named using its 1st logFileTag argument, by calling the auto_log function.
- Uses echo -e where the -e argument to echo enables interpretation of backslash escapes.
- e.g. "\nt" will be interpreted as a newline, tab character and "\tn" will be interpreted as a tab characternewline
- Calls stdStreams with its 2nd and 3rd arguments.
- Calls echo capturing its output in a local variable using backtick execution syntax, then displays the captured text.
- Calls the echo_se function with some text.
- Calls the echo_se function again, capturing its output in a local variable, then displays the captured text.
Code Block | ||
---|---|---|
| ||
# function that illustrates auto-logging and capturing function output # arg 1 - (required) tag to identify the logfile # arg 2 - (optional) text for standard output # arg 3 - (optional) text for standard error function testAutolog() { local logFileTag="$1" local outTxt=${2:-"text for standard output"} local errTxt=${3:-"text for standard error"} auto_log "$logFileTag" echo -e "\n1) Call stdStreams with output and error text:" stdStreams "$outTxt" "$errTxt" echo -e "\n2) Capture echo output in a variable and display it:" local output=`echo $outTxt` echo -e " echo output was:\n$output" echo -e "\n3) Call echo_se with error text:" echo_se "$errTxt" echo -e "\n4)Capture echo_se function output in a variable and display it:" output=`echo_se "$errTxt"` echo -e "echo_se output was: '$output'" } |
exercise 4
Call the testAutoLog testAutolog command with no further command line arguments. What happens, and why?
...
What log file is produced, what ? What are its contents, and why?
...