echo printing -e in bash

后端 未结 2 951
灰色年华
灰色年华 2020-12-19 20:47

I\'ve gotten this script I\'ve created in Bash, and one of the functions I\'m using is echo and I\'m using the -e flag for interpretations of

相关标签:
2条回答
  • 2020-12-19 21:31

    You wrote, "I've gotten this script I've created in Bash", but you haven't told us exactly what you mean by that.

    UPDATE : The question has been updated. The script's first line is #!/bin/sh. Read on for an explanation and solution.

    I can reproduce the problem on my system by including your code in a script starting with

    #!/bin/sh
    

    I can correct the problem by changing that first line to

    #!/bin/bash
    

    /bin/sh on my system happens to be a symlink to dash. The dash shell has echo as a builtin command, but it doesn't support the -e option. The #! line, g othe

    There are numerous implementations of the echo command: most shells provide it as a builtin command (with various features depending on the shell), and there's likely to be an external command /bin/echo with its own subtly different behavior.

    If you want consistent behavior for printing anything other than a simple line of text, I suggest using the printf command. See https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo (cited by Josh Lee in a comment).

    The #! line, known as a shebang, controls what shell is used to execute your script. The interactive shell you execute the script from is irrelevant. (It pretty much has to be that way; otherwise scripts would behave differently for different users). In the absence of a #! line, a script will (probably) be executed with /bin/sh, but there's not much point in not being explicit.

    0 讨论(0)
  • 2020-12-19 21:48

    Remove the trailing backslashes and add a closing quote:

    NC='\033[31;0m'       # no colors or formatting
    RED='\033[0;31;1m'    # print text in bold red
    PUR='\033[0;35;1m'    # print text in bold purple
    YEL='\033[0;33;1m'    # print text in bold Yellow
    GRA='\033[0;37;1m'    # print text in bold Gray
    echo -e "This ${YEL}Message${NC} has color\nwith ${RED}new${NC} lines."
    

    And it works as expected in bash.

    If you save this script into a file, run it like bash <file>.


    Try type -a echo to see what it is. The first line of output should be echo is a shell builtin:

    $ type -a echo
    echo is a shell builtin
    echo is /usr/bin/echo
    echo is /bin/echo
    
    0 讨论(0)
提交回复
热议问题