5

I have a bunch of variables that I want to check, and if they contain the value "None" then I want to empty them.

    var1=(check for some value, sometimes it returns "none")
    var2=(check for some value, sometimes it returns "none")
    var3=(check for some value, sometimes it returns "none")
    someBizzareName=(check for some value, sometimes it returns "none")

    if [[ "${var1}" == "None" ]] ; then
        var1=""
    fi
    if [[ "${var2}" == "None" ]] ; then
        var2=""
    fi

And this is all working fine and dandy, only since I have a lot of varN, I will end up with a ton of if [[ "${varN}" == "None" ]] and I have to know their names ; so I was wondering, since it's in BASH very nature to search and match everything, if there is a wild-card for variables, inside a for loop, that will match all vars, something like ${*} (I tried that, does'nt work) ? I have done all kinds of searches but always find something about matching variable content, not the var itself..?

yPhil
  • 8,049
  • 4
  • 57
  • 83

3 Answers3

8

All, no. But you can match a pattern (but not *).

$ echo "${!B*}"
BASH BASHOPTS BASHPID BASH_ALIASES BASH_ARGC BASH_ARGV BASH_CMDS BASH_COMMAND BASH_LINENO BASH_SOURCE BASH_SUBSHELL BASH_VERSINFO BASH_VERSION
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

You may also use the builtin compgen:

man bash | less -p 'compgen .option. .word.'
compgen -A variable B
jim
  • 21
  • 1
1

All, yes ;-)

Most Unix/Linux support either the env or printenv which produce output like

 var=value

The export command, without arguments, will list all exported variables in your environment.

for varAndVal in $( env ) ; do
   case ${varAndVal} in
     *=none ) 
      eval \$${varAndVal}=
      #OR eval unset \$${varAndVal}
     ;;
    esac
 done

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

shellter
  • 36,525
  • 7
  • 83
  • 90
  • This does not quite do what I want ; It matches (really just lists them) environment vars, when I want not only to match vars local to my script (obviously) but if possible, local to my for loop, just to be safe – yPhil May 12 '11 at 10:40
  • Yes, sorry, missed the part about for loop. Good luck! – shellter May 12 '11 at 11:15