[英]Bash: “printf %q $str” deletes spaces when in scripts. (Alternatives?)
printf %q should quote a string. printf%q应该引用一个字符串。 However, when executed into a script, it deletes the spaces.
但是,当执行到脚本中时,它会删除空格。
This command: 这个命令:
printf %q "hello world"
outputs: 输出:
hello\ world
which is correct. 哪个是对的。
This script: 这个脚本:
#!/bin/bash
str="hello world"
printf %q $str
outputs: 输出:
helloworld
which is wrong. 这是错的。
If such behavior is indeed expected, what alternative exists in a script for quoting a string containing any character in a way that it can be translated back to the original by a called program? 如果确实需要这样的行为,那么在脚本中有什么替代方法可以引用包含任何字符的字符串,以便可以通过被调用的程序将其转换回原始字符?
Thanks. 谢谢。
Software: GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu) 软件:GNU bash,版本4.1.5(1)-release(i486-pc-linux-gnu)
EDITED: Solved, thanks. 编辑:解决了,谢谢。
You should use: 你应该使用:
printf %q "$str"
Example: 例:
susam@nifty:~$ cat a.sh
#!/bin/bash
str="hello world"
printf %q "$str"
susam@nifty:~$ ./a.sh
hello\ world
When you run printf %q $str
, the shell expands it to: 当您运行
printf %q $str
,shell会将其扩展为:
printf %q hello world
So, the strings hello
and world
are supplied as two separate arguments to the printf
command and it prints the two arguments side by side. 因此,字符串
hello
和world
作为printf
命令的两个独立参数提供,它并排打印两个参数。
But when you run printf %q "$str"
, the shell expands it to: 但是当你运行
printf %q "$str"
,shell会将其扩展为:
printf %q "hello world"
In this case, the string hello world
is supplied as a single argument to the printf
command. 在这种情况下,字符串
hello world
作为printf
命令的单个参数提供。 This is what you want. 这就是你想要的。
Here is something you can experiment with to play with these concepts: 以下是您可以尝试使用这些概念的内容:
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
Try 尝试
printf %q "${str}"
in your script. 在你的脚本中。
This worked for me. 这对我有用。 Satisfies these requirements
满足这些要求
#! /bin/bash FOO='myTest3$; t%^&;frog now! and *()"' FOO=`printf "%q" "$FOO"` # Has \ chars echo $FOO # Eat all the \ chars FOO=$(printf "%q" "$FOO" | sed "s/\\\\//g") # Strip \ chars echo $FOO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.