Skip to content

Instantly share code, notes, and snippets.

@maximkott
Created November 7, 2016 09:20
Show Gist options
  • Save maximkott/6529f77cde87a1a4146b8ee91321ffa2 to your computer and use it in GitHub Desktop.
Save maximkott/6529f77cde87a1a4146b8ee91321ffa2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# @help Write an error message and exit.
# @usage error <message>
error() {
local message=$1; shift;
printf "\e[01;31merror: $message\e[0m\n" >&2;
exit 1;
}
# @help Output piped to this function is formatted and printed.
# @usage wrap_out <lines..>
wrap_out() {
while read line; do
echo " > $line"
done
}
# @help Output piped to this function is formatted and printed.
# @usage wrap_err <lines...>
wrap_err() {
while read line; do
printf "\e[01;31m > $line\e[0m\n" >&2
done
}
# @help Run any command and format output.
# @usage cmd <command>
cmd() {
echo
echo " # $@"
(cd "$PWD" && (eval $@) 2>&1 1>&3 3>&- | wrap_err) 3>&1 1>&2 | wrap_out
echo
}
# @help Run any command from the PROJECT_PATH
# directory and format output.
# @return cmdcd <command>
cmdcd() {
local path=$1; shift
echo
echo " # $@"
(cd "$path" && (eval $@) 2>&1 1>&3 3>&- | wrap_err) 3>&1 1>&2 | wrap_out
echo
}
# @help Return absolute path of a file or directory.
# @usage realpath <path>
# @return absolute file path
realpath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
# @help Prompts user for input and writes answer in
# to the target variable. Will not prompt if
# INTERACTIVE has been disabled. If the target
# already contains either "y" or "n", then that
# value is used. If the DEFAULT_ANSWER is defined,
# then this value is used as the answer. Otherwise
# user is prompted for input.
# @usage ask <question> <answer>
ask() {
local question="$1"
local answer="$2"
# ${!...} is used to retrieve a value
# trough the variable name (indirect expansion)
case ${!answer} in
y|n);;
*)
if [[ "$DEFAULT_ANSWER" ]]; then
eval "$answer=$DEFAULT_ANSWER"
return
fi
if [[ "$INTERACTIVE" == "y" ]]; then
read -p "$question" $answer
return
fi
;;
esac
}
# @help Prompts user for input and writes answer in
# to the target variable. Will not prompt if
# INTERACTIVE has been disabled. If the target
# already contains either "y" or "n", then that
# value is used. Otherwise user is prompted for
# input.
# @usage ask <question> <answer>
prompt() {
local question="$1"
local answer="$2"
# ${!...} is used to retrieve a value
# trough the variable name (indirect expansion)
if [[ ! ${!answer} && "$INTERACTIVE" == "y" ]]; then
read -p "$question" "$answer"
return
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment