3

I ran my script using three ways and the output was different, could you explain to me why it works like that? Thanks!! Here is my script

#!/bin/bash
#Program:
#     This program shows "Hello World!" in your screen.
echo -e "Hello World! \a\n" 
exit 0

And if i run it by bash and ./ like bash sh01.sh the output is

Hello World!

However, if i use sh like sh sh01.sh it would be like

-e Hello World!

And Here is some other information

  1. OS: Ubuntu 16.04.3
  2. type sh -> dash
pynexj
  • 19,215
  • 5
  • 38
  • 56
Lincoln
  • 33
  • 3
  • 2
    Bash is a very extended shell, while Dash is a very basic and standard compliant shell. That means Bash can add extended versions of standard commands, like `echo` which according to the standard only takes *one* optional argument (and it isn't `-e`). See [this official POSIX reference about `echo`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html) for more information. – Some programmer dude Oct 29 '17 at 03:44
  • Related: https://stackoverflow.com/questions/35603323/bash-different-between-printf-and-echo – codeforester Oct 29 '17 at 03:52
  • I got it , Thank you!!! – Lincoln Oct 30 '17 at 13:29

1 Answers1

2

echo is not very portable (even Bash's echo may behave differently on different OSes which may use different default options when compiling Bash). You can use printf. According to posix:

It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted. The printf utility can be used portably to emulate any of the traditional behaviors of the echo utility [...]

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • Yeah, a bunch of my scripts that used `echo -n` broke when OS X v10.5 shipped with `bash` compiled with different options. They switched it back in some later update, but I don't know exactly when because I'd switched all my scripts to use `printf` instead. `printf` is a bit more complicated to use than `echo`, but *way* more predictable. – Gordon Davisson Oct 29 '17 at 06:17
  • Thank you! Later , i meet some similar situation again, like newgrp, behaves differently in ubuntu and OSX. TT . Now i have why hh – Lincoln Oct 30 '17 at 13:31