Search code examples
bashtcsh

Looping through array of filenames in bash and read them


I have an array that contains paths of files. Each of these files has a single line. I would like to loop through the array, and for each file read the line in it and store it in a variable. I tried this

f1=$1
f2=$2
filenames[0]=${f1}
filenames[1]=${f2}
for filename in "${filenames[@]}"
do
  # get the filename
  set fl = `basename $filename`
  echo ${fl}
  # read its contents (one line)
  set filecontent = `cat ${fl}`
  echo ${filecontent}
done

both echos display blank spaces. If I do

echo `basename $filename`

it does display the filename. What is wrong with the loop above?


Solution

  • The basic problem is that you seem to be mixing bash and tcsh syntax -- and just by chance you're using tcsh commands that happen not to be syntax errors in bash, but don't do what you want.

    This:

    set fl = `basename $filename`
    

    is how you'd set $fl to the basename of $filename in tcsh. In bash, however, the set command is quite different. Since it's not what you need to use here anyway, I won't go into details, but you can read about them here.

    In bash, the way to set a variable is just

    var=value  # NO spaces around the "="
    

    Also, bash, unlike tcsh, has a $(command) syntax to capture the output of a command, in addition to the older `command`.

    So your command

    set fl = `basename $filename`
    

    should be

    fl="$("basename $filename")"
    

    Adding double quotes around both the $filename reference and the $(...) command substitution ensures that the shell can handle odd characters in the file name and/or command output.