JohnP
JohnP

Reputation: 109

How to echo a variable (name of which contains another varibale)

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.

Upvotes: 0

Views: 1093

Answers (3)

JohnP
JohnP

Reputation: 109

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

Upvotes: 1

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

Upvotes: 1

Luuk
Luuk

Reputation: 14958

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

Upvotes: 0

Related Questions