Changes

Bash Shell Script Examples

2,644 bytes added, 17:48, 25 February 2021
The following lines were added (+) and removed (-):
=== three expression control loop === #!/bin/bash for (( c=1; c<=5; c++ )) do    echo "Welcome $c times" done echo $1===Stopwatch=== <nowiki>BEGIN=$(date +%s)</nowiki> <nowiki></nowiki> <nowiki>echo Starting Stopwatch...</nowiki> <nowiki>echo Press Q to exit.</nowiki> <nowiki></nowiki> <nowiki>while true; do</nowiki> <nowiki>    NOW=$(date +%s)</nowiki> <nowiki>    let DIFF=$(($NOW - $BEGIN))</nowiki> <nowiki>    let MINS=$(($DIFF / 60))</nowiki> <nowiki>    let SECS=$(($DIFF % 60))</nowiki> <nowiki>    let HOURS=$(($DIFF / 3600))</nowiki> <nowiki>    let DAYS=$(($DIFF / 86400))</nowiki> <nowiki></nowiki> <nowiki>    # \r  is a "carriage return" - returns cursor to start of line</nowiki> <nowiki>    printf "\r%3d Days, %02d:%02d:%02d" $DAYS $HOURS $MINS $SECS</nowiki> <nowiki></nowiki> <nowiki># In the following line -t for timeout, -N for just 1 character</nowiki> <nowiki>    read -t 0.25 -N 1 input</nowiki> <nowiki>    if [[ $input = "q" ]] || [[ $input = "Q" ]]; then</nowiki> <nowiki># The following line is for the prompt to appear on a new line.</nowiki> <nowiki>        echo</nowiki> <nowiki>        break </nowiki> <nowiki>    fi</nowiki> <nowiki>done</nowiki>=== Press any key to continue === read -n 1 -s -r -p "Press any key to continue"=== DateTime Code === #!/bin/bash PDATE=`date '+%Y%m%d%H%M%S'` echo $PDATE=== Terminate execution of script on command error ===While your shell script executes commands one might return a non-zero value.  At the top of your shell script use set -eThis will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.Works with redirects too, such as command > output.txtDoes not work with pipes command | anothercommand parameterThe set -e directive is sometimes insufficient for example if you have pipes.  If your script contains commands with pipes then include set -e set -o pipefailRather than the entire script under the influence of set -e you can use an exit on non-zero just on specific command lines in the script command || exit 1Or say you use to use a script wide set -e and exclude a particular line from causing the script to exit if that one particular command fails badcommand || trueEven if badcommand exits non-zero the script will go on, while set -e was specified at the top. The || true will make the command pipeline have a true return value even if the command fails so the the -e option will not kill the script.On errors, you can also use 'trap' with the pseudo-signal ERR
Bureaucrat, administrator
16,192
edits