Bash脚本引用问题 [英] Bash script quote issues

查看:87
本文介绍了Bash脚本引用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Bash脚本:

  DIR =〜/ Folder / With\ Spaces 
CMD = find $ DIR -type f
#回显显示隐藏字符
echo $ CMD | cat -v
而读取行

echo $ line
完成< <($ CMD)

输出:

 查找〜/ Folder / With\空格-type f 
找到:〜/ Folder / With\:没有这样的文件或目录
找到:空格:没有这样的文件或目录

我经历了我能想到的所有方法,



如果我正确理解这一点,那么CMD应该是以下内容:



p>

 找到〜/ Folder / With\ Spaces -type f 

这应该可以正常工作,并且由于查找不能在路径中使用引号,因此这是正确的方法它。回声显示它与此匹配。在命令行中键入此字符串可以正常工作。同样, echo 命令将打印此内容。但是脚本的输出表明还有其他事情在发生,可能是在执行命令的 行上。



在这种情况下,我如何让Bash将文件名解释为一个路径?又为什么呢反斜杠(以防止将其解释为由空格分隔的两个部分)被视为字符串的一部分,因此它将在何处拆分,为什么?

解决方案

Bash永远不会将数据作为代码进行评估,但是它会做一些可能会让您以为是事实的事情(即分词和遍历)。由于 \ 是shell语法的一部分,因此在扩展变量时不会将其重新解释为转义序列。



这是应该怎么做:

  DIR =〜/ 文件夹/带空格#〜不会用引号引起来,并且没有 \。 
CMD =(查找 $ DIR -type f)#使用数组跟踪单词

#打印转义的单词,以便您知道实际执行的内容
printf%q $ {CMD [@]} | | cat -v
echo

,而IFS =读-r行#不要拆分或解释单词

echo $ line#使用引号来防止遍历和单词拆分
完成< <( $ {CMD [@]})#在数组中运行命令,而不会出现空格问题


I have the following Bash script:

DIR="~/Folder/With\ Spaces"
CMD="find $DIR -type f"
# echo showing hidden characters
echo $CMD | cat -v
while read line
do
    echo $line
done < <($CMD)

The output:

find ~/Folder/With\ Spaces -type f
find: ~/Folder/With\: No such file or directory
find: Spaces: No such file or directory

I've gone through this every way I can think of, with single and double quotes, backslash and no backslash, quotes around the variable in the other lines, no dice.

If I understand this correctly, CMD should be the following:

find ~/Folder/With\ Spaces -type f

This should work fine, and since find can't use quotes around its path, this is the correct way to do it. The echo shows it matches this. Typing this string into the command line works fine. Again, the echo command prints this. But the output of the script says there's something else going on, probably on the done line where the command is being executed.

How would I get Bash to interpret the filename as one path in this context? And why? The backslash (to stop it from interpreting it as two parts separated by spaces) is being treated as part of the string, so where is it splitting it, and why?

解决方案

Bash never evaluates data as code, but it does some things that could make you think it does (namely word splitting and globbing). Since \ is part of shell syntax, it's not reinterpretted as an escape sequence when you expand the variable.

Here's how you should do it:

DIR=~/"Folder/With Spaces"  # ~ doesn't expand in quotes, and there's no "\". 
CMD=(find "$DIR" -type f)   # use an array to keep track of words

# Print the words escaped so you know what will actually be executed
printf "%q " "${CMD[@]}" | cat -v
echo

while IFS= read -r line  # don't split or interpret words 
do
    echo "$line"         # use quotes to prevent globbing and word splitting
done < <("${CMD[@]}")    # run the command in the array without spacing issues

这篇关于Bash脚本引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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