简体   繁体   English

如何在Linux shell中的for…in语句中使用字符串作为参数

[英]how to use a string as an argument in an for … in … statement in linux shell

I'm familiar with the structure of 我熟悉

for file in foo/folder\ with\ spaces/foo2/*.txt
do
    #do some stuff...
done

However, I want to put foo/folder with spaces/foo2/*.txt into a variable and then use it. 但是,我想将foo/folder with spaces/foo2/*.txt放入变量中,然后使用它。 Something like this: 像这样:

myDirectory="foo/folder with spaces/foo2/*.txt"

for file in $myDirectory
do
    # do some stuff
done

But what I've written here doesn't work, and it won't work even if I do 但是我在这里写的东西行不通,即使我这样做也行不通

myDirectory="food/folder\ with\ spaces/foo2/*.txt"

or 要么

for file in "$myDirectory" ...

Any help? 有什么帮助吗? is this even possible? 这有可能吗?

don't parse ls 不要解析ls

# your files are expanded here
# note lack of backslashes and location of quotes
myfiles=("food/folder with spaces/foo2/"*.txt)

# iterate over the array with this
for file in "${myfiles[@]}"; do ...

Parsing ls is a bad idea, instead just do the shell globbing outside of the quotes. 解析ls是一个坏主意,而只是在引号之外进行shell遍历。

You could also do: 您也可以这样做:

$mydir="folder/with spaces"

for file in "$mydir"/*; do
  ...
done

Also look into how find and xargs works. 还要研究findxargs工作原理。 Many of these sort of problems can be solved using those. 使用这些可以解决许多这类问题。 Look at the -print0 and -0 options in particular if you want to be safe. 为了安全起见,请特别注意-print0-0选项。

Try using the ls command in the for loop. 尝试在for循环中使用ls命令。 This works for me: 这对我有用:

for file in `ls "$myDirectory"`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM