0

I am looking for a way to echo names and values of all env variables that start with nlu_setting, so the output might look like:

nlu_setting_json=true
nlu_setting_global=0
nlu_setting_bar=foo

does anyone know how to do this?

  • Environment variables? Or shell variables? The difference is important, as it rules in/out several answers. – JdeBP Aug 4 '18 at 8:45
3
for var in "${!nlu_setting_@}"; do
    printf '%s=%s\n' "$var" "${!var}"
done

The expansion ${!nlu_setting_@} is a bash-specific expansion that returns a list of variable names matching a particular prefix. Here we use it to as for all names that start with the string nlu_setting_. We loop over these names and output the name along with the value of that variable.

We get the value of the variable using variable indirection (${!var}).

  • do you think this is better than the compgen solution? – Alexander Mills Aug 4 '18 at 7:47
  • @AlexanderMills I would say that it will be more efficient as it's not calling grep. Your solution would also pick up variable names that contain nlu_setting_ anywhere, not just at the start of the variable name (due to the non-anchored regular expression that you are using). – Kusalananda Aug 4 '18 at 7:53
  • ah yes good point – Alexander Mills Aug 4 '18 at 17:11
0

After looking at the answers to this question, I came up with this:

   compgen -A variable | grep "nlu_setting_" | while read v; do
            echo "$v = ${!v}";
   done

it seems to work. Never heard of the compgen command, but if it's universal bash built-in, it should be all good..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.