user1002430
user1002430

Reputation:

Difference in calling printf from sh and bash

I am having trouble understanding the difference between the output of the two scripts below and would like someone to explain why there's a difference.

Script 1:

#!/bin/bash
f() {
    x=$(printf "%q" "$1")
    echo "x = $x"
}
f 'he\llo'

This outputs: x = he\\llo

Script 2:

#!/bin/sh
f() {
    x=$(printf "%q" "$1")
    echo "x = $x"
}
f 'he\llo'

This outputs: x = he\llo

Probably, sh doesn't have a built-in printf and is using /usr/bin/printf while bash does have a built-in printf. But I don't get the significance of how this makes the output different.

Upvotes: 0

Views: 4836

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 81012

This is echo behaving like echo -e in whatever shell you have as sh.

$ cat test.sh
f() {
    x="$(printf "%q" "$1")"
    declare -p x
    echo "echo: x = $x"
    echo -e "echo -e: x = $x"
    printf 'printf: x = %s\n' "$x"
}
f 'he\llo'

$ /bin/bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

$ /bin/bash test.sh
declare -- x="he\\\\llo"
echo: x = he\\llo
echo -e: x = he\llo
printf: x = he\\llo

$ /bin/sh test.sh
declare -- x="he\\\\llo"
echo: x = he\\llo
echo -e: x = he\llo
printf: x = he\\llo

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295649

printf %q is explicitly a bash extension, not present in POSIX printf.

Thus, the behavior you get from any implementation other than that provided by bash is undefined.

Upvotes: 2

Related Questions