Bash scripts


It can manipulate paths in multiple different ways

  1. Print paths relative to a base

    realpath --relative-to=<base> <path>
    1. Do not expand symlinks
      realpath --no-symlinks <path>
    2. Check that the full path exists
      realpath --canonicalize-existing <path>

Prompt before each command

Useful for risky, often-run scripts. Add one of these snippets to the top of your script:


trap 'read -p "run: $BASH_COMMAND"' DEBUG

Fancy (colored)

if which -v tput 2>&1 > /dev/null; then
    PROMPTCOLOR="$(tput bold)$(tput setaf 3)"
    RESETCOLOR="$(tput sgr0)"

function debug_prompt() {
    read -p "$PROMPTCOLOR|$(basename "$0")|$RESETCOLOR $BASH_COMMAND"
trap 'debug_prompt' DEBUG

Prompt before running some command

confirm() {
    while true; do
        read -p "[$(basename $0)] $1 | (yn)> " yn
        case $yn in
            [Yy]* ) eval "$1"; break ;;
            [Nn]* ) return 1 ;;
            * ) echo "Please answer yes or no.";;

Use as

confirm "command --to --run"

Surround output in a box

box() {
    # read from stdin and dump to a temporary file
    while read -r INPUT; do
        echo $INPUT >> $TMPFILE

    # get the length of the longest line
    END=$(awk '{if(length($0)>l) l=length($0);}END{print l}' $TMPFILE)

    # add 1 to our end length
    LASTCHAR=$(expr $END + 1)

    # create header and footer
    FHLENGTH=$(expr $LASTCHAR + 3)
    HEADER="┏"$(seq -s "━" "$FHLENGTH" | sed 's/[0-9]//g')"┓"
    FOOTER="┗"$(seq -s "━" "$FHLENGTH" | sed 's/[0-9]//g')"┛"

    # make the output pretty
    echo $HEADER
    while read OUTPUT; do
        printf "┃ %-${LASTCHAR}s ┃\n" "$OUTPUT"
    done < $TMPFILE
    echo $FOOTER

    # done
    rm -f $TMPFILE

Use as

ls -l | box