0

I have a shell program that has content like this

!#/bin/bash

echo \\n program

Once I run this program on a platform other than Linux it recognizes the special character and gives the output as

(newline)
program

When the same program runs on Linux, the echo command needs the "-e" option. Now I don't want to change each occurrence of echo with "echo -e" in my file explicitly because then this will start creating issues on other platforms. So I want to do a conditional compilation like

set SYSTEM="uname -s"

#if ($SYSTEM == Linux)
set echo="echo -e"
#endif

but this does not work because using the set or export command, I need to replace all occurrences of echo with $echo, which I don't want to do. Again setting aliases does not solve this issue as i need echo to be replaced with "echo -e" even in subshell.

Is there any other way around with which I can substitute echo with "echo -e" only for Linux platform?

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
  • 3
    Is switching to using `printf` for portability an option? – Wrikken Apr 05 '13 at 20:15
  • 1
    Do you have a bash script, or do you really have a sh script? If you're sure it's always bash, echo is a builtin, and it can be configured to work the same way on all systems. If it could be run by other shells too, consider `printf` as per Wrikken's comment. –  Apr 05 '13 at 20:24

4 Answers4

1

Using a combination of BASH_ENV and a function we can do:

bash-3.2$ export BASH_ENV=$HOME/always-source
bash-3.2$ cat $HOME/always-source 
echo() {
    command echo -e "$@"
}

bash-3.2$ cat runme.bash
#!/bin/bash

echo "\nHello World $1\n"

if [[ -z $1 ]]; then
    $0 child
fi

And an invocation:

bash-3.2$ ./runme.bash 

Hello World 


Hello World child

Wrapping this in a bash test (linux & mac os x):

if [[ $(uname -s) = Linux ]] || [[ $(uname -s) = Darwin ]]; then
    export BASH_ENV=$HOME/always-source
fi
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
0

I belive you are looking for an alias.

The syntax in bash would be alias echo='echo -e';

gbtimmon
  • 4,238
  • 1
  • 21
  • 36
0

I understand you don't want to change the echo calls, but how do you think about using echo $'\nhello\n' instead of echo -e?

escitalopram
  • 3,750
  • 2
  • 23
  • 24
0

Define an alias in your shell:

alias echo="echo -e";

then source your script:

source ./<script1>

By doing this, your script will not create a subshell and use the variables of the parent shell. Also, variables which you define in your script will exist even after termination of your script.

For invoking other scripts in script1.sh, use source:

source ./<script2>
A human being
  • 1,220
  • 8
  • 18