Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 696
Zasito Avatar asked Jan 18 '26 12:01

Zasito


1 Answers

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
like image 130
Arkku Avatar answered Jan 21 '26 03:01

Arkku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!