Skip to content

Instantly share code, notes, and snippets.

@fuji44
Created December 16, 2022 10:33
Show Gist options
  • Save fuji44/8a46741c429fc6c732d2409ef4f4fc73 to your computer and use it in GitHub Desktop.
Save fuji44/8a46741c429fc6c732d2409ef4f4fc73 to your computer and use it in GitHub Desktop.
Snippet code for Boolean-like use of environment variables in shell scripts

Snippet code for Boolean-like use of environment variables in shell scripts

#!/bin/sh

debug=$(echo "${BATCH_DEBUG:=false}" | tr "[:upper:]" "[:lower:]")
if [ "$debug" = "true" ] || [ "$debug" = "1" ]; then
  echo "TRUE -> $debug"
else
  echo "FALSE -> $debug"
fi

Execution Result.

$ ./sample.sh 
FALSE -> false
$ BATCH_DEBUG=true ./sample.sh 
TRUE -> true
$ BATCH_DEBUG=True ./sample.sh 
TRUE -> true
$ BATCH_DEBUG=TRUE ./sample.sh 
TRUE -> true
$ BATCH_DEBUG=trUE ./sample.sh 
TRUE -> true
$ BATCH_DEBUG=false ./sample.sh 
FALSE -> false
$ BATCH_DEBUG=False ./sample.sh 
FALSE -> false
$ BATCH_DEBUG=F ./sample.sh 
FALSE -> f
$ BATCH_DEBUG=T ./sample.sh 
FALSE -> t
$ BATCH_DEBUG=0 ./sample.sh 
FALSE -> 0
$ BATCH_DEBUG=1 ./sample.sh 
TRUE -> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment