20
4
For some shell sessions I want to be able to print a warning flag if a shell variable is not set and exported.
It is fairly simple to do something like this to print "Error" in the prompt if SET_ME
is unset or null.
test_var () { test -z "$1" && echo Error; }
PS1='$(test_var "$SET_ME") \$ '
However this fails to flag if I set SET_ME
without exporting it, which is an error that I want to be able to detect. Short of something like $(bash -c 'test -z "$SET_ME" && echo Error;')
or grepping the output of export
, is there a simple check that I can do to test whether SET_ME
has been exported?
A non-POSIX, bash-only solution is completely acceptable.
I think that this is what I'm looking for. In theory, the re might need to be more flexible, e.g. if I had a read-only exported variable, but in practice I never use other
typeset
attributes. – CB Bailey – 2012-07-19T13:36:09.483Good point. I'll fix it for posterity. – chepner – 2012-07-19T13:40:32.730
It looks like attempting to quote the regular expression stops it working as a regular expression in bash >= 3.2. – CB Bailey – 2012-07-19T14:14:50.023
Also there's an inconsistency,
-z "$1"
assumes I'm passing the value of a variable totest_var
(as I was) whereasdeclare -p
expects its name. I came up with this test which takes the name of a shell variable:test_exported_notnull () { re='^declare -\w*x'; [[ -n $(eval echo \$$1) ]] && [[ $(declare -p "$1") =~ $re ]]; }
. – CB Bailey – 2012-07-19T14:51:38.527To avoid the
eval
, just add this first line:var=$1
, then use[[ -z "${!var}" ]] && echo Error
. – chepner – 2012-07-19T16:00:33.060