Bash Script – Echo Env Variables Starting with nlu_setting

bashenvironment-variablesshellvariable

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?

Best Answer

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 ask 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}).

Related Question