0

I have a question regarding how a variable can be called with another variable name inside a loop.

The following script does not work:

#!/bin/bash
# Comparing test1.txt with test2.txt, test1.ini with test2.ini, test1.conf with test2.conf

FIRSTFILE1=test1.txt;
SECONDFILE1=test2.txt;
FIRSTFILE2=test1.ini;
SECONDFILE2=test2.ini;
FIRSTFILE3=test1.conf;
SECONDFILE3=test2.conf;

for NUM in {1..3};
do
  diff --brief <(sort $FIRSTFILE$NUM) <(sort $SECONDFILE$NUM) > /dev/null
  value=$?
  if [ $value -eq 1 ]
  then
    echo "different"
  else
    echo "identical"
  fi
done
1

Not an explanation to the question if it is strictly about combining to variables into one but the following would give you a working result of iterating through your files:

for EXT in txt ini conf;
do
  diff --brief <(sort test1.${EXT}) <(sort test2.${EXT}) > /dev/null
  value=$?
  if [ $value -eq 1 ]
  then
    echo "different"
  else
    echo "identical"
  fi
done
  • Thanks for your answer. This was helpful if test1/2 are just the names of the files. I had test1/2 defined as variables from user input and looping the file extension doesn't work in my real script. – JJadmin Sep 18 '15 at 17:45
2

You are looking for indirect parameter expansion. You can achieve this in bash using an exclamation point.

#!/bin/bash                                                                        
FIRSTFILE1=test1.txt;
SECONDFILE1=test2.txt;
FIRSTFILE2=test1.ini;
SECONDFILE2=test2.ini;
FIRSTFILE3=test1.conf;
SECONDFILE3=test2.conf;

for NUM in {1..3};
do
    a=FIRSTFILE$NUM
    b=SECONDFILE$NUM
    echo ${!a}
    echo ${!b}
done

You will need some more testing to find a oneliner :). For more information see: http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

  • Thanks for your answer. This works fine for me. It may take more time to find one liner and what you describe is exactly what I'm looking for, "indirect parameter expansion". – JJadmin Sep 18 '15 at 17:41
1

Use arrays, because that is what they are for:

#!/bin/bash

first=(  test1.txt test1.ini test1.conf )
second=( test2.txt test2.ini test2.conf )

for (( i = 0; i < ${#first[@]}; ++i )); do
    if cmp -s "${first[i]}" "${second[i]}"; then
        echo 'same'
    else
        echo 'different'
    fi
done

Or, if your filenames are all this predictable,

#!/bin/bash

suffixes=( .txt .ini .conf )

for suffix in "${suffixes[@]}"; do
    if cmp -s "test1$suffix" "test2$suffix"; then
        echo 'same'
    else
        echo 'different'
    fi
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.