dicle
dicle

Reputation: 1152

How to have a global variable that has been read from a list that has filenames in bash?

I have one txt file that has bunch of class names.

I would like to read those class names line by line in bash script and assign that value to a variable to use it globally in another command in the script.

FILES="files.txt"

for f in $FILES
do
  echo "Processing $f file..."
  # take action on each file. $f store current file name
  cat $f
done

Upvotes: 0

Views: 610

Answers (3)

Paul Hodges
Paul Hodges

Reputation: 15246

I'm assuming files.txt is a list of the class files, one class per line?

while read class
do : whatver you need with $class
done < files.txt

If you have more than one file of classes, use an array.
Don't make it all caps.

file_list=( files.txt other.txt ) # put several as needed
for f in "${file_list[@]}" # use proper quoting
do : processing $f # set -x for these to log to stderr
   while read class
   do : whatver you need with $class
   done < "$f"
done

Upvotes: 1

Adam vonNieda
Adam vonNieda

Reputation: 1745

Example 1

FILES="files.txt" 
cat $FILES | while read class
do
   echo $class  # Do something with $class
done

Example 2, as commented by Paul Hodges

FILES="files.txt"
while read class
do
   echo $class  # Do something with $class
done < $FILES

Upvotes: 0

nullPointer
nullPointer

Reputation: 4574

Assuming each line in your files contain only a class name, this should do it :

for f in $FILES
do
  echo "Processing $f file..."
  while read class
  do 
    <something with "$class" >
  done < $f
done

Upvotes: 0

Related Questions