将文件名分配给Shell中的变量 [英] Assign file names to a variable in shell

查看:761
本文介绍了将文件名分配给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.

我希望通过for循环将目录中文件列表的每个名称分配给一个变量(同一变量,一次一次),然后在循环中执行一些操作,看看会发生什么意思是:

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

假设这个scrypt名为Scrypt,我有一个名为Folder的文件夹,并且在A,B,C内有3个文件.我希望它在我写这篇文章时在终端上显示给我:

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

以下内容:

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)

那是问题

推荐答案

一种方法是使用通配符扩展代替ls,例如

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

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

这假定$1是其中包含文件的目录的路径.

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

如果只想处理纯文件,请在do之后的一行添加检查标记:

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

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

这篇关于将文件名分配给Shell中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆