如何传递bash中包含空格的变量作为循环参数? [英] How to pass a variable containing space in bash as a loop argument?
问题描述
美好的一天,我正在创建一个脚本来读取路径的子文件夹/目录的一级.脚本是这样的:
#loopdir.sh为我在`ls -d $ 1`中做回声$ i完毕
但是,当我尝试使用它读取/media/My \ Passport/时,它会将参数读取为两个不同的目录:
$ ./loopdir.sh/media/My \ Passport/ls:无法访问/media/My:没有此类文件或目录护照/
尝试代替执行此操作(我的理解是您要列出子目录,对吗?):
for i in"$ 1"/*;做回显"$ {i%/}"完毕
解析 ls
输出是一个坏主意:它是用于交互式查看文件信息的工具.它的输出是为人类格式化的,将导致脚本中的错误.使用glob或find代替.了解原因: http://mywiki.wooledge.org/ParsingLs
(最后但并非最不重要):使用更多报价!</strong>它们至关重要.另外,了解'和'和`之间的区别.请参见 http://mywiki.wooledge.org/Quotes和 http://wiki.bash-hackers.org/syntax/words > good day,
I am creating a script to read one level of subfolders/directories of a path. The script is like so: But when I tried to use it to read /media/My\ Passport/, it reads the argument as two different dirs:
Try doing this instead (my understanding is that you want to list subdirs, Am I right?) : Parsing And (last but not least) : USE MORE QUOTES! They are vital. Also, learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes and http://wiki.bash-hackers.org/syntax/words 这篇关于如何传递bash中包含空格的变量作为循环参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!#loopdir.sh
for i in `ls -d $1`
do
echo $i
done
$ ./loopdir.sh /media/My\ Passport/
ls: cannot access /media/My: No such file or directory
Passport/
for i in "$1"/*; do
echo "${i%/}"
done
ls
output is a bad idea : it's is a tool for interactively looking at file information. Its output is formatted for humans and will cause bugs in scripts. Use globs or find instead. Understand why: http://mywiki.wooledge.org/ParsingLs