Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active January 10, 2016 06:46
Show Gist options
  • Save kjbrum/63f621eb4d063ffeb8ea to your computer and use it in GitHub Desktop.
Save kjbrum/63f621eb4d063ffeb8ea to your computer and use it in GitHub Desktop.
A collection of useful bash functions.
# Variables used
RED=$(tput setaf 1);
GREEN=$(tput setaf 2);
YELLOW=$(tput setaf 3);
WHITE=$(tput setaf 7);
# Throw an error
error() {
printf "${RED}Error:${WHITE} ${1}\n"
exit
}
# Throw a warning
warn() {
printf "${YELLOW}${1}${WHITE}\n"
exit
}
# Throw a success message
success() {
printf "${GREEN}${1}${WHITE}\n"
}
# Remove the trailing slash from a string, if it exists
strip_trailing_slash() {
result="$1"
if [[ "$1" == */ ]]; then
result=$(echo "$1" | rev | cut -c 2- | rev)
fi
echo "$result"
}
# Escape characters in a string
escape() {
printf "%q " $1
}
# URL encode a string
rawurlencode() {
local string="${1}"
local strlen=${#string}
local encoded=""
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
echo "${encoded}"
}
# Print a message like a typewriter
typewrite() {
MESSAGE_TYPE="$1"
MESSAGE="$2"
case $MESSAGE_TYPE in
'success' )
printf "${GREEN}"
;;
'warn' )
printf "${YELLOW}"
;;
'error' )
printf "${RED}"
;;
'normal' )
;;
* )
error "Error: Message type \"$MESSAGE_TYPE\" doesn't exist."
exit
;;
esac
SPOT=0
while true; do
printf "${MESSAGE:SPOT:1}"
SPOT=$(($SPOT+1))
# Generate a random decimal
DELAY_INT=$(( ( RANDOM % 10 ) + 1 ))
sleep "0.0$DELAY_INT"
if [ ${#MESSAGE} -eq "$SPOT" ]; then
printf "${WHITE}"
printf "\n"
break
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment