问题
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
回答1:
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
回答2:
http://mywiki.wooledge.org/ParsingLs
Use globbing instead:
for filename in "$1"/* ; do
<cmd> "$filename"
done
Note the quotes around $filename
回答3:
It's a bit unclear what you are trying to accomplish, but you can essentially do the same thing with functionality that already exists with find
. For example, the following prints the contents of each file found in a folder:
find FolderName -type f -maxdepth 1 -exec cat {} \;
回答4:
well, i think that what you meant is that the loop will show the filenames in the desired dir. so, i would do it like that:
for filename in "$1"/*; do
echo "file: $filename"
done
that way the result should be (in case in the dir are 3 files and the names are A B C:
`file: A
`file: B
`file: C
来源:https://stackoverflow.com/questions/13519442/assign-file-names-to-a-variable-in-shell