在bash中保留变量中的特殊字符(使用确切的字符)

时间:2017-07-20 00:38:31

标签: bash

我在设置变量时尝试保留变量中的特殊字符。我试图将文件路径保存为变量。例如:

提示

用户输入

点击并拖动您的文件

/ Users / leetbacon / Desktop / My \ Stuff / time \ to \ fly \ \& \ soar.png

您选择/ Users / leetbacon / Desktop / My \ Stuff / time \ to \ fly \ \& \ soar.png

相反,每当我输入文件时,它总是像这样输出(我不想要):

您选择/ Users / leetbacon / Desktop / My Stuff / time to fly& soar.png

有什么方法可以让它存储我想要的变量吗?

这是我现在的代码:

echo 'click and drag your file here'
read -p " " FilepatH
echo 'You chose '"$FilepatH"

我想保留所有特殊字符。我只是想编写一个可以涵盖文件名所有可能性的脚本。

我正在使用OS X Yosemite

- 托德

2 个答案:

答案 0 :(得分:1)

  

我希望保留所有特殊字符。

完成。在您发布的脚本中,所有字符都会被保留。

您可以通过运行来验证它们是否真正保留:

ls "$FilepatH"

这只会因为保留所有特殊字符而起作用。如果它们没有被保存下来就行不通,就找不到文件了。

但是,您可能希望通过输出澄清意图:

echo "You chose '$FilepatH'"

这将打印:

You chose '/Users/leetbacon/Desktop/My Stuff/time to fly & soar.png'

答案 1 :(得分:0)

您可以通过使用read(" raw")选项告诉-r跳过解析(和删除)转义和引号。但是,正如大家所说,你不想这样做。在分配给shell变量的值中嵌入转义和/或引号并没有做任何有用的事情,因为shell在扩展变量时不会解析它们。有关某人特别遇到问题的示例,请参阅this question,因为他们在尝试使用的文件名中嵌入了转义符。

以下是这样做的一个例子:

$ cat t1.sh
#!/bin/bash
echo 'click and drag your file here'
read -p " " FilepatH
echo 'You chose '"$FilepatH"
echo
echo "Trying to use the variable with double-quotes:"
ls -l "$FilepatH"

$ ./t1.sh
click and drag your file here
 /Users/gordon/weird\ chars\:\ \'\"\\\(\)\&\;.txt 
You chose /Users/gordon/weird chars: '"\()&;.txt

Trying to use the variable with double-quotes:
-rw-r--r--  1 gordon  staff  0 Jul 19 22:56 /Users/gordon/weird chars: '"\()&;.txt

这里做错了(read -r):

$ cat t2.sh
#!/bin/bash
echo 'click and drag your file here'
read -r -p " " FilepatH
echo 'You chose '"$FilepatH"
echo
echo "Trying to use the variable with double-quotes:"
ls -l "$FilepatH"
echo
echo "Trying to use the variable without double-quotes:"
ls -l $FilepatH

$ ./t2.sh 
click and drag your file here
 /Users/gordon/weird\ chars\:\ \'\"\\\(\)\&\;.txt 
You chose /Users/gordon/weird\ chars\:\ \'\"\\\(\)\&\;.txt

Trying to use the variable with double-quotes:
ls: /Users/gordon/weird\ chars\:\ \'\"\\\(\)\&\;.txt: No such file or directory

Trying to use the variable without double-quotes:
ls: /Users/gordon/weird\: No such file or directory
ls: \'\"\\\(\)\&\;.txt: No such file or directory
ls: chars\:\: No such file or directory

请注意,对于双引号中的变量,它尝试将转义视为文件名的文字部分。没有它们,它会根据空格将文件路径拆分为单独的项目,然后仍然将转义视为文件名的文字部分。

相关问题