Bash scripts
Realpath
It can manipulate paths in multiple different ways
Print paths relative to a base
realpath --relative-to=<base> <path>
- Do not expand symlinks
realpath --no-symlinks <path>
- Check that the full path exists
realpath --canonicalize-existing <path>
- Do not expand symlinks
Prompt before each command
Useful for risky, often-run scripts. Add one of these snippets to the top of your script:
Simple
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)"
fi
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.";;
esac
done
}
Use as
confirm "command --to --run"
Surround output in a box
box() {
# read from stdin and dump to a temporary file
TMPFILE=$(mktemp)
while read -r INPUT; do
echo $INPUT >> $TMPFILE
done
# 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