单引号和$ in string bash

ASh*_*hah 0 bash

我运行下面的脚本在函数内的文件路径上运行一些检查一些路径包含单引号,临时文件包含"$"如果我将变量括在单引号(下面的名称变量)中,那么字符串将被截断是一个'在文件路径中.如果我在文件路径周围使用双引号,那么如果路径中有"$"则会截断.这个循环难题有什么办法吗?

File=/root/fed/~$reader.txt
Run Code Online (Sandbox Code Playgroud)

回声就好像文件路径中有$

/root/fed/eager.txt
Run Code Online (Sandbox Code Playgroud)

如果有一个'在文件路径中,我附上单引号(以阻止上述发生)然后

File='/root/fed/reader's'
(this wont echo)
Run Code Online (Sandbox Code Playgroud)

代码是:

find / -type f -print0 | xargs -0 -I name bash -c "fnchash 'name'" 

fnchash () {
    echo "$1"
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ger 6

单引号字符串可能不包含单引号.甚至没有逃脱它们.未引用或双引号和非转义$引入了一个变量引用,该引用扩展为引用的shell变量的值,如果没有定义此类变量则引入任何内容.

一种解决方案涉及双引号和转义字符.例如:

File=/root/fed/~\$reader.txt
File=/root/fed/reader\'s
File="/root/fed/\$reader's.txt"
Run Code Online (Sandbox Code Playgroud)

请注意,引号不一定是字符串分隔符 - 它们是子字符串分隔符.因此,这些工作也是如此:

File=/root/fed/~'$'reader.txt
File=/root/fed/reader"'"s
Run Code Online (Sandbox Code Playgroud)

如果您需要在运行时自动引用读取的数据,那么您还应该了解bash内置printf命令(它比您作为独立命令的功能更具特色).特别要注意,字%q段描述符对其参数执行所有必需的引用,以使它们可以作为shell输入重用.

printf '%q' $File
Run Code Online (Sandbox Code Playgroud)