1

When I run these lines in my terminal on macOS I get the correct result

hex=$(echo -n 'betty' | xxd -p) echo $hex 6265747479 

but when I run them in a bash script I get something completely different

sh myscript.sh 62657474790a 

It's like its put a carriage return on the end for some reason. WHY?

4
  • Can't reproduce. Please add the output of cat myscript.sh; sh myscript.sh Commented Aug 24, 2017 at 6:57
  • @Peter: First, it's not a carriage return, it is a line feed. Secondly, it seems that different shells are involved. In your second example, you provide sh as a shell, and we don't know where sh is linked to on your machine. If both are bash shells, they might be different versions (do a print $BASH_VERSION in both variants), which implement the echo in a different way. Commented Aug 24, 2017 at 13:13
  • I'm surprised that echo -n 'betty' would produce that output, which appears to be betty followed by a newline. I'd expect either betty without a newline, or -n betty with a newline. What exactly does sh -c 'echo -n betty' print, compared to echo -n betty? What does ls -l /bin/sh say? Commented Aug 24, 2017 at 15:58
  • sh -c 'echo -n betty' gives me -n betty echo -n betty gives me betty with the next prompt on the same line as betty ls -l /bin/sh => -r-xr-xr-x 1 root wheel 630464 29 Apr 10:31 /bin/sh Commented Aug 28, 2017 at 3:08

2 Answers 2

2

Different versions of echo do different things when given -n as their first argument. Some print it as part of their output, some interpret it as a flag, who knows what's going to happen. According to the POSIX standard for echo, "If the first operand is -n, or if any of the operands contain a backslash character, the results are implementation-defined."

The most reliable way to print a string without a linefeed after it is with printf. It's slightly more complicated because you have to give it a format string as well as the string you want printed:

hex=$(printf "%s" 'betty' | xxd -p) 
Sign up to request clarification or add additional context in comments.

1 Comment

I see, so even though they are the same command the runtime (sic) can deal with them in different ways.
1

Try bash instead of sh. As echo is a builtin command, it depends on the shell how it is executed. For me, the echo from sh does not seem to support -n:

sh-3.2$ echo -n hello -n hello sh-3.2$ echo $(echo -n 'betty' | xxd -p) 2d6e2062657474790a 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.