User Tools

Site Tools


bash

This is an old revision of the document!


Bash

Useful Bash code, with no particular order

Add safeguards on every script

At the top of the file, always start your scripts with:

set -euo pipefail
  • -e: The -e option will cause a bash script to exit immediately when a command fails.
  • -o pipefail: This particular option sets the exit code of a pipeline to that of the rightmost command to exit with a non-zero status, or to zero if all commands of the pipeline exit successfully.
  • -u: This option causes the bash shell to treat unset variables as an error and exit immediately.

More info: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/

Read passwords with feedback on a script

unset password
charcount=0
prompt="Enter your password: "
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
        break
    fi
    if [[ $char == $'\177' ]] ; then # Backspace support
        if [ $charcount -gt 0 ] ; then
            charcount=$((charcount-1))
            prompt=$'\b \b'
            password="${password%?}"
        else
            prompt=''
        fi
    else
        charcount=$((charcount+1))
        prompt='*'
        password+="$char"
    fi
done
bash.1673965671.txt.gz · Last modified: 2024/11/17 12:59 (external edit)