LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to make cascading 2 variables valid? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-make-cascading-2-variables-valid-920918/)

sscn 12-28-2011 12:26 PM

How to make cascading 2 variables valid?
 
Hi,

I want to make below define valid in my script.

F1="123456"
F2="abcdef"

for (( i = 1; 1 < 3; i++ ))
do
echo "Search $F{$i} string ......"
grep -r $F{$i} /etc/
done

But I cannot get the expected result $F1 and $F2 in 1st and 2nd time.

How I can make it?

Thx,

sscn

jschiwal 12-28-2011 12:52 PM

It would be easier to use arrays.
Code:


F=("123456" "abcdef")
for ((i = 0; i<2; i++)); do
  echo "Searching ${F[$i]} string ..."
  grep "${F[$i]}" /etc/*
done

However doing it your way, you need to use `eval' and escape the `$' sign.
eval grep -r \$F$i /etc/

To see how the arguments are evaluated, and passed on to a command, replace the command with `set' and then echo $*.
set grep -r \$F$i /etc/
echo $*
grep -r $F1 /etc/

sscn 12-28-2011 01:40 PM

Great!
 
Hi jschiwal,

So nice to get it work. I like array method.

For eval, I updated my script as below but it couldn't work as array method did.

for (( i = 1; 1 < 3; i++ ))
do

echo "Search \$F$i string ......"
eval grep -r \$F$i /etc/

done


All times are GMT -5. The time now is 06:42 AM.