如何传递bash中包含空格的变量作为循环参数? [英] How to pass a variable containing space in bash as a loop argument?

查看:79
本文介绍了如何传递bash中包含空格的变量作为循环参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我正在创建一个脚本来读取路径的子文件夹/目录的一级.脚本是这样的:

 #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:

#loopdir.sh
for i in `ls -d $1`
do
echo $i
done

But when I tried to use it to read /media/My\ Passport/, it reads the argument as two different dirs:

$ ./loopdir.sh /media/My\ Passport/
ls: cannot access /media/My: No such file or directory
Passport/

解决方案

Try doing this instead (my understanding is that you want to list subdirs, Am I right?) :

for i in "$1"/*; do
    echo "${i%/}"
done

Parsing 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

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屋!

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