Skip to content

Instantly share code, notes, and snippets.

@dmgolembiowski
Created June 1, 2025 20:59
Show Gist options
  • Save dmgolembiowski/ac6b4e12cb294b6912c2277922679c81 to your computer and use it in GitHub Desktop.
Save dmgolembiowski/ac6b4e12cb294b6912c2277922679c81 to your computer and use it in GitHub Desktop.
ternary shell operator cli: https://stackoverflow.com/a/35512445/11944425
#!/usr/bin/env bash
# Retrieved from https://stackoverflow.com/a/35512445/11944425
# solution provider Brad Parks https://stackoverflow.com/users/26510/brad-parks
function show_help()
{
ME=$(basename "$0")
IT=$(cat <<EOF
Returns a ternary result
usage: BOOLEAN VALUE_IF_TRUE VALUE_IF_FALSE
e.g.
# YES
$ME 1 YES NO
# NO
$ME 0 YES NO
# NO
$ME "" YES NO
# YES
$ME "STRING THAT ISNT BLANK OR 0" YES NO
# INFO contains NO
INFO=\$($ME 0 YES NO)
EOF
)
echo "$IT"
echo
exit
}
if [ "$1" = "help" ] || [ "$1" = '?' ] || [ "$1" = "--help" ] || [ "$1" = "h" ]; then
show_help
fi
if [ -z "$3" ]
then
show_help
fi
# Set a default value for what is "false" -> 0
FALSE_VALUE=${4:-0}
function main
{
if [ "$1" == "$FALSE_VALUE" ] || [ "$1" = '' ]; then
echo $3
exit;
fi;
echo $2
}
main "$1" "$2" "$3"
@dmgolembiowski
Copy link
Author

Install via:

curl --output-dir "/dev/shm" -o tern https://gist.githubusercontent.com/dmgolembiowski/ac6b4e12cb294b6912c2277922679c81/raw/c6e5a20626f687a785f08b7d293fb3c30123c2ea/tern
chmod +x /dev/shm/tern && \
sudo install -m 775 /dev/shm/tern /usr/local/bin/tern
rm /dev/shm/tern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment