Bash:"printf%q $ str"在脚本中删除空格.(备择方案?)

Ele*_*ena 11 bash printf

printf%q应该引用一个字符串.但是,当执行到脚本中时,它会删除空格.

这个命令:

printf %q "hello world"
Run Code Online (Sandbox Code Playgroud)

输出:

hello\ world
Run Code Online (Sandbox Code Playgroud)

哪个是对的.

这个脚本:

#!/bin/bash

str="hello world"
printf %q $str
Run Code Online (Sandbox Code Playgroud)

输出:

helloworld
Run Code Online (Sandbox Code Playgroud)

这是错的.

如果确实需要这样的行为,那么脚本中有什么替代方法可以引用包含任何字符的字符串,以便可以通过被调用的程序将其转换回原始字符?

谢谢.

软件:GNU bash,版本4.1.5(1)-release(i486-pc-linux-gnu)

编辑:解决了,谢谢.

Sus*_*Pal 37

你应该使用:

printf %q "$str"
Run Code Online (Sandbox Code Playgroud)

例:

susam@nifty:~$ cat a.sh
#!/bin/bash

str="hello world"
printf %q "$str"
susam@nifty:~$ ./a.sh 
hello\ world
Run Code Online (Sandbox Code Playgroud)

运行时printf %q $str,shell会将其扩展为:

printf %q hello world
Run Code Online (Sandbox Code Playgroud)

因此,字符串helloworld作为printf命令的两个单独参数提供,它并排打印两个参数.

但是当你运行时printf %q "$str",shell会将其扩展为:

printf %q "hello world"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,字符串hello world作为printf命令的单个参数提供.这就是你想要的.

以下是您可以尝试使用这些概念的内容:

susam@nifty:~$ showargs() { echo "COUNT: $#"; printf "ARG: %s\n" "$@"; }
susam@nifty:~$ showargs hello world
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "hello world"
COUNT: 1
ARG: hello world
susam@nifty:~$ showargs "hello world" "bye world"
COUNT: 2
ARG: hello world
ARG: bye world
susam@nifty:~$ str="hello world"
susam@nifty:~$ showargs $str
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "$str"
COUNT: 1
ARG: hello world
Run Code Online (Sandbox Code Playgroud)