How to escape a NULL byte as an argument to a shell command inside a Makefile

不羁的心 提交于 2019-12-01 08:57:22

问题


Inside a Makefile I run a shell command which I want to pass a NULL byte as argument. The following attempt fails:

echo $(shell /bin/echo -n $$'\x00' | ruby -e "puts STDIN.read.inspect")

It generates:

echo "$\\x00"

Instead I expected:

echo "\u0000"

How do I properly escape such a NULL byte?


回答1:


echo disables interpretation of backslash escapes by default. You need to supply the -e option to enable it.

$ echo -ne "\x00" | ruby -e "puts STDIN.read.inspect"
"\u0000"



回答2:


Due to the execve(2) semantics it is not possible to pass a string containing a null byte as argument. Each argument string is terminated by null byte, therefore making it impossible to distinguish between the contained null byte and the end of the string.




回答3:


These uses of echo are totally non-portable. Use printf, it's much easier to use for anything other than the simplest strings, and much more portable.

$ cat makefile
all:
        printf '\0' > foo.out
        od -a foo.out

$ make
printf '\0' > foo.out
od -a foo.out
0000000 nul
0000001



回答4:


If anyone else came here looking how to escape a null via a shell command in ruby backticks:

irb(main):024:0> `curl --silent http://some-website-or-stream.com | sed 's/\\x0//g' 1>&2`
=> ""


来源:https://stackoverflow.com/questions/17105225/how-to-escape-a-null-byte-as-an-argument-to-a-shell-command-inside-a-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!