Home > Back-end >  How can I loop through a list of files, from directories specified in a variable?
How can I loop through a list of files, from directories specified in a variable?

Time:02-03

I am trying to loop through the files in some directories, and performa an action on each file.

The list of directories is specified by a list of strings, stored as an environment variable

LIST_OF_DIRECTORIES=dir1 dir2 dir3

for dir in $LIST_OF_DIRECTORIES; do
  for file in $dir/* ; do
      echo $file
  done
done

This results in nothing. I'm expecting all of the files within that directory to be echoed.

I am basing my logic off of Bash For-Loop on Directories, and trying to make this work for my use case.

CodePudding user response:

You have to place strings with spaces around quotes otherwise each "word" will be interpreted separately. In your example, LIST_OF_DIRECTORIES=dir1 is executed (dir1 is indeed assigned LIST_OF_DIRECTORIES), but because it precedes a now interpreted simple command (dir2 dir3), it only lives temporarily for that command.

You should do either of these instead:

LIST_OF_DIRECTORIES="dir1 dir2 dir3"
LIST_OF_DIRECTORIES='dir1 dir2 dir3'

From Simple Command Expansion:

If no command name results, the variable assignments affect the current shell environment. In the case of such a command (one that consists only of assignment statements and redirections), assignment statements are performed before redirections. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status.

Also as a suggestion, use arrays for storing multiple entries instead and don't use word splitting unless your script doesn't use filename expansion and noglob is enabled with set -f or shopt -so noglob.

LIST_OF_DIRECTORIES=(dir1 dir2 dir3)

for dir in "${LIST_OF_DIRECTORIES[@]}"; do

Other References:

CodePudding user response:

This will work fine for you as.

LIST_OF_DIRECTORIES="dir1 dir2 dir3"
for dir in $LIST_OF_DIRECTORIES;
#add all the files to the files variable
do        files=`ls $dir`;
for file in $files;
#Take action on your file here, I am just doing ls for my file here. 
do echo `ls $dir/$file`;
done;
done
  •  Tags:  
  • bash
  • Related