Home > Software design >  How to echo a variable (name of which contains another varibale)
How to echo a variable (name of which contains another varibale)

Time:12-07

I was writing a small shell script to read and print lines of a file.

#!/bin/csh

set IN_FILE=$1
set i=1
foreach line ( "`cat $IN_FILE`" )
  set F$i="`echo $line`"
  echo ${F${i}}
  @ i = $i   1
end

Upon executing, I am getting the following error

Missing '}'.

I was wondering how to echo a variable, which contains another variable in its name.

CodePudding user response:

I don't have csh, so tried this with bash. The content of test.sh is:

i=1
eval "F$i=\"this is a line\""
eval echo "test: " \${F$i}
echo "F1 is" $F1

and it seems to work:

 /tmp$ ./test.sh
 test: this is a line
 F1 is this is a line

CodePudding user response:

Found an example here: https://www.unix.com/shell-programming-and-scripting/275206-issue-nesting-variables-csh.html and tried to adapt it to your script

Try:

#!/bin/csh

set IN_FILE=$1
set i=1
set j=1
foreach line ( "`cat $IN_FILE`" )
  #set F$i="`echo $line`"
  #echo ${F${i}}
  set test=( F${i} )
  echo "$test[$j]"
  @ i = $i   1
end

found an example here: https://www.unix.com/shell-programming-and-scripting/275206-issue-nesting-variables-csh.html

and tried to adapt it to your script

CodePudding user response:

Fixed it.

#!/bin/csh

set IN_FILE=$1
set i=1
foreach line ( "`cat $IN_FILE`" )
  eval "set F$i='`echo $line`'"
  eval echo \${F$i}
  @ i = $i   1
end

Thanks a lot linuxfan for the tip

  • Related