简体   繁体   English

在Linux上用“ echo -e”代替命令echo

[英]Substituting command echo with “echo -e” on linux

I have a shell program that has content like this 我有一个shell程序,其内容如下

!#/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 一旦我在Linux以外的平台上运行该程序,它就会识别特殊字符并将输出显示为

(newline)
program

When the same program runs on Linux, the echo command needs the "-e" option. 当同一程序在Linux上运行时,echo命令需要使用“ -e”选项。 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. 现在,我不想在文件中用“ echo -e”显式更改每次出现的回声,因为这将开始在其他平台上引起问题。 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. 但这是行不通的,因为使用set或export命令,我需要用$ echo替换所有出现的echo,但我不想这样做。 Again setting aliases does not solve this issue as i need echo to be replaced with "echo -e" even in subshell. 再次设置别名不能解决此问题,因为即使在子外壳中,我也需要将echo替换为“ echo -e”。

Is there any other way around with which I can substitute echo with "echo -e" only for Linux platform? 是否有其他方法可以仅在Linux平台上将echo替换为“ echo -e”?

Using a combination of BASH_ENV and a function we can do: 结合使用BASH_ENV和函数,我们可以执行以下操作:

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): 将其包装在bash测试中(Linux和Mac OS X):

if [[ $(uname -s) = Linux ]] || [[ $(uname -s) = Darwin ]]; then
    export BASH_ENV=$HOME/always-source
fi

I belive you are looking for an alias. 相信您正在寻找别名。

The syntax in bash would be alias echo='echo -e'; bash中的语法为alias echo='echo -e';

我知道您不想更改echo调用,但是您如何考虑使用echo $'\\nhello\\n'代替echo -e

Define an alias in your shell: 在您的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: 要在script1.sh中调用其他脚本,请使用source:

source ./<script2>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM