Echo -e acts differently when running in root script on ubuntu

When I run the bash script on ubuntu 9.10, I get a different behavior from the bash echo "-e" option, depending on whether I am running as root.

Consider this script:

$ cat echo-test
if [ "`whoami`" = "root" ]; then
  echo "Running as root" 
fi
echo Testing /bin/echo -e
/bin/echo -e "foo\nbar"
echo Testing bash echo -e
echo -e "foo\nbar"

When starting as a non-root user, I see this output:

$ ./echo-test 
Testing /bin/echo -e
foo
bar
Testing bash echo -e
foo
bar

When I start as root, I see this output:

$ sudo ./echo-test 
Running as root
Testing /bin/echo -e
foo
bar
Testing bash echo -e
-e foo
bar

Note that in the latter case, “-e” is reflected in “case-foo” instead of “foo” in the second line). When running the script as root, the echo command works as if "-e" had been specified, and if -e was given, the parameter itself would be an echo.

/bin/echo bash echo, , bash echo , .

- , ? bash ?

FYI - GNU bash, 4.0.33 (1) -release (x86_64-pc-linux-gnu)

+3
3

, bash ? "shebang" (#!/bin/ bash) script

+4

POSIXLY_CORRECT , xpg_echo .

if test -n "${POSIXLY_CORRECT+yes}"; then
    pc="set '$POSIXLY_CORRECT'"
else
    pc=unset
fi
echo POSIXLY_CORRECT: "$pc"
shopt -q xpg_echo && xe=set || xe=unset
echo xpg_echo: $xe

, :

{ n=1
for p in '' p; do
    for x in '' x; do
        for e in '' e; do
            printf "\nmode: ${p:-_}${x:-_}${e:-_}\n"
            test -n "$x" && xx=-s || xx=-u
            bash ${p:+--posix} -c "              shopt $xx xpg_echo
              test -n \"\${POSIXLY_CORRECT+yes}\" && pc=\"set '\$POSIXLY_CORRECT'\" || pc=unset
              shopt -q xpg_echo && xe=set || xe=unset
              echo POSIXLY_CORRECT: \"\$pc\"
              echo xpg_echo: \$xe
              echo${e:+ -e} \"$n\n$((n+1))\"
            "
            n=$((n+2))
        done
    done
done
}

" root" ( POSIXLY_CORRECT xpg_echo ).

mode: ___
POSIXLY_CORRECT: unset
xpg_echo: unset
1\n2

mode: __e
POSIXLY_CORRECT: unset
xpg_echo: unset
3
4

mode: _x_
POSIXLY_CORRECT: unset
xpg_echo: set
5
6

mode: _xe
POSIXLY_CORRECT: unset
xpg_echo: set
7
8

mode: p__
POSIXLY_CORRECT: set 'y'
xpg_echo: unset
9\n10

mode: p_e
POSIXLY_CORRECT: set 'y'
xpg_echo: unset
11
12

mode: px_
POSIXLY_CORRECT: set 'y'
xpg_echo: set
13
14

mode: pxe
POSIXLY_CORRECT: set 'y'
xpg_echo: set
-e 15
16

, printf .

  • " (.. normative) POSIX echo , , escape- .

    printf echo.

  • . GNU Autoconf.

  • ( ) , printf ksh.
    , ksh , .

  • Apple Shell printf .

printf , , , , , .

, :

printf 'foo\nbar'
printf '%s\n%s' foo bar

, , , (, , , ).

+1

Ubuntu 9.10 onward uses the trait as a standard shell instead of bash.

Dash can be thought of as a lightweight alternative to bash, but has a slight incompatibility. You must explicitly indicate bash with the "Shebang" sign

0
source

Source: https://habr.com/ru/post/1747604/


All Articles