Table of Contents

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

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