linuxshellunixksh

Shell script - How to display variable names and their values in loop


I am trying to display variable names and their values in a for loop, through a ksh shell script. But I'm not sure how to do that. Should I use something like eval for this?

Here is an example script:

#!/bin/ksh

A=var1
B=var2
C=var3
D=var4

param=""

for i in A B C D
do
        param="$param -p \"$i=\$i\""
done

echo "$param"

The output of above script is -p "A=$i" -p "B=$i" -p "C=$i" -p "D=$i".

The desired output is -p "A=var1" -p "B=var2" -p "C=var3" -p "D=var4"

I tried it using eval but that doesn't seem to work. It fails with syntax errors.


Solution

  • You can use a different method in KornShell (ksh) if you wish to avoid using eval in your script, which is generally a good practice to avoid security issues and potential errors. A reference to another variable can be created using Ksh's nameref feature, which functions similarly to a pointer in other programming languages.

    Here's how to change your script so that nameref is used in instead of eval:

    #!/bin/ksh
    
    A=var1
    B=var2
    C=var3
    D=var4
    
    param=""
    
    for i in A B C D
    do
            nameref varref=$i
            param="$param -p \"$i=$varref\""
    done
    
    echo "$param"
    

    Varref is referenced to the variable named by $i when nameref varref=$i. This indicates that the variable (such as A, B, etc.) is used as an alias for varref. In reality, you are accessing the variable that varref references when you modify it. Next, you create your param string by assigning the variable name, i, to the variable and the value, varref.

    This should make your script safer and possibly less error-prone by producing the intended result, -p "A=var1" -p "B=var2" -p "C=var3" -p "D=var4", without the need for eval.