Search code examples
bashshellvariablesfor-loopls

Assign file names to a variable in shell


I'm trying to write a script that does something a bit more sophisticated than what I'm going to show you, but I know that the problem is in this part.

I want each name of a list of files in a directory to be assigned to a variable (the same variable, one at a time) through a for loop, then do something inside of the loop with this, see what mean:

for thing in $(ls $1);
do
    file $thing;
done

Edit: let's say this scrypt is called Scrypt and I have a folder named Folder, and it has 3 files inside named A,B,C. I want it to show me on the terminal when I write this:

./scrypt Folder

the following:

A: file
B: file
C: file

With the code I've shown above, I get this:

A: ERROR: cannot open `A' (No such file or directory)
B: ERROR: cannot open `B' (No such file or directory)
C: ERROR: cannot open `C' (No such file or directory)

that is the problem


Solution

  • One way is to use wildcard expansion instead of ls, e.g.,

    for filename in "$1"/*; do
        command "$filename"
    done
    

    This assumes that $1 is the path to a directory with files in it.

    If you want to only operate on plain files, add a check right after do along the lines of:

    [ ! -f "$filename" ] && continue