Search code examples
linuxbashechocommand-line-arguments

Shell script -e command line argument not recognized


Using -e as a flag in a command bash file isn't recognized. Let's say we have a bash file named server.sh, which only echoes all the passed arguments:

server.sh

echo "$@"

Here are the results so far when server.sh is executed with an -e as a first argument:

./server.sh -e hello ## output: hello
./server.sh -eeeee world ## output: world
./server.sh -eeeeeeeeeeeee what ## output: what

Any other arguments are valid except for arguments that starts with an -e. Can anyone tell me the reason why this is happening? And is there a way to make the -e argument be recognized in server.sh?


Solution

  • Here's an easier way to reproduce your problem:

    $ echo "-e" "foo"
    foo             # What happened to "-e"?
    

    echo parsing your intended output as options is one of the reasons why POSIX warns against this command in portable scripts.

    If you are trying to dump the parameters for logging and debugging purposes, you can use bash's printf %q:

     #!/bin/bash   
     # (does not work with sh)
     printf '%q ' "$0" "$@"
     printf '\n'
    

    This will escape output the arguments in such a way that you can copy-paste it back to the shell to reproduce it later (quoting changes, but the arguments will be identical):

    $ ./myscript -e -avx --arg "my long arg" '(!#%^)(!*'
    ./myscript -e -avx --arg my\ long\ arg \(\!#%\^\)\(\!\*
    

    If you actually do want to write out the arguments separated by spaces in an ambiguous form, you can use:

    #!/bin/sh
    # works with bash and POSIX sh
    printf '%s\n' "$*"
    

    This results in:

    $ ./myscript -e -avx --arg "my long arg" '(!#%^)(!*'
    -e -avx --arg my long arg (!#%^)(!*