Issue
how can I check and replace whole bunch of variable with a for loop than doing individual if condition in bash a=one b=two c=three d=four e=null something like this I have over 40. I need to check each variable if found null should replace with 0
for I in a b c d e
do
if [ ${!I} == 'null' ]; then
#would like to set that variable = 0 (example e=0)
fi
done
Solution
You can use a nameref variable with a for loop.
From the documentation:
A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see Bash Builtins) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value.
[...]
If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed.
For example:
#!/usr/bin/env bash
a=null
b=1
c=null
# Outputs null 1 null
printf "%s\n" "$a" "$b" "$c"
# Make v a nameref
declare -n v
for v in a b c; do
if [[ $v == null ]]; then
v=0
fi
done
# Outputs 0 1 0
printf "%s\n" "$a" "$b" "$c"
Answered By - Shawn