Search code examples
bashshellmacos-sierra

bash vs sh script different results


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?


Solution

  • 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)