在 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

--托德

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

做。在您发布的脚本中,将保留所有字符。

您可以通过运行以下命令来验证它们是否确实保留:

ls "$FilepatH"

这仅在保留所有特殊字符时才有效。如果不保留它们,它将不起作用,将找不到该文件。

但是,您可能希望通过输出阐明意图:

echo "You chose '$FilepatH'"

这将打印:

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

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

下面是正确执行此操作的示例:

$ 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

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

最新更新