Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Over Files in Variable Path (Bash)

Tags:

bash

shell

glob

I was looking for the best way to find iterate over files in a variables path and came across this question.

However, this and every other solution I've found uses a literal path rather than a variable, and I believe this is my problem.

for file in "${path}/*"
do
     echo "INFO - Checking $file"
     [[ -e "$file" ]] || continue
done

Even though there are definitely files in the directory (and if i put one of the literal paths in place of ${path} I get the expected result), this always only iterates once, and the value of $file is always the literal value of ${path}/* without any globbing.

What am I doing wrong?

like image 742
Jordan Mackie Avatar asked Jun 26 '18 13:06

Jordan Mackie


People also ask

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do you loop through every file in a directory?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.

What does $@ mean in a shell script?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

Glob expansion doesn't happen inside quotes (both single and double) in shell.

You should be using this code:

for file in "$path"/*; do
     echo "INFO - Checking $file"
     [[ -e $file ]] || continue
done
like image 126
anubhava Avatar answered Oct 11 '22 16:10

anubhava