3

I'm writing a shell script that appends binary contents to a file. I tried using this command:

echo -en '\x61\x62\x63..' >> /tmp/myfile

but that caused the following output:

-en \x61\x62\x63..

Is there any way I could append the contents to a file rather than having to remove all contents every time?

Note

I'm trying to do this on a system that only has /bin/sh, this command works fine with bash but not when using the default shell.

Paradoxis
  • 153

2 Answers2

1

In bash, echo is a builtin function, so you are getting that behavior. In sh it is not a builtin. Looks like sh uses its builtin "echo" command which is different.

So try using /bin/echo rather than without the /bin/.

rocky
  • 1,998
  • Is there a way I could still do this with another command? I found something about printf but I cant seem to get that working either – Paradoxis Jun 20 '15 at 19:12
1

If you want to stick with portability, you can't use echo or printf, both treat escape sequences \xXX unspecified as POSIX defined.

Even in GNU system, the behavior of echo, either builtin or /bin/echo can be alter. You can try:

$ POSIXLY_CORRECT=1 /bin/echo -en '\x61'
-en \x61

$ env BASHOPTS=xpg_echo POSIXLY_CORRECT=1 bash -c "echo -en '\x61'"
-en a

(You should read this for more details).

With standard POSIX tool chest, you can use awk:

$ awk 'BEGIN{printf "%c%c%c..", 97, 98, 99}'
abc..
cuonglm
  • 153,898