Skip to content

Instantly share code, notes, and snippets.

@mrjk
Last active December 31, 2023 02:25
Show Gist options
  • Save mrjk/31a2fb90c445fe516b0ae41eea7297ea to your computer and use it in GitHub Desktop.
Save mrjk/31a2fb90c445fe516b0ae41eea7297ea to your computer and use it in GitHub Desktop.
Bash library utils
yaml2json ()
{
python -c 'import yaml, json, sys ; print(json.dumps(yaml.safe_load(sys.stdin.read())))'
}
json2yaml ()
{
python -c 'import yaml, json, sys; print(yaml.dump(yaml.safe_load(sys.stdin.read()), indent=2))' input.yaml
}
grep_ip ()
{
grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
}
load_colors ()
{
bold=$(tput bold)
underline=$(tput sgr 0 1)
reset=$(tput sgr0)
purple=$(tput setaf 171)
red=$(tput setaf 1)
green=$(tput setaf 76)
tan=$(tput setaf 3)
blue=$(tput setaf 38)
}
user_ask () {
printf "\n${bold}$@${reset}"
read -p " (y/n) " -n 1
printf "\n"
}
# Test whether the result of an 'ask' is a confirmation
is_confirmed() {
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
return 0
fi
return 1
}
# See: https://github.com/martinburger/bash-common-helpers/blob/master/bash-common-helpers.sh
assert_root_user ()
{
if [[ ${EUID} -ne 0 ]]; then
return 1
fi
}
assert_command ()
{
local cmd=${1}
type ${cmd} >/dev/null 2>&1 || return 1
}
function cmn_ask_to_continue {
local msg=${1}
local waitingforanswer=true
while ${waitingforanswer}; do
read -p "${msg} (hit 'y/Y' to continue, 'n/N' to cancel) " -n 1 ynanswer
case ${ynanswer} in
[Yy] ) waitingforanswer=false; break;;
[Nn] ) echo ""; cmn_die "Operation cancelled as requested!";;
* ) echo ""; echo "Please answer either yes (y/Y) or no (n/N).";;
esac
done
echo ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment