2

I've recently been working with positional parameters in some bash scripts and I've noticed that -e and -n do not appear to be passed as positional parameters. I've been searching through documentation but haven't been able to figure out why. Consider the following short scripts:

#!/bin/bash
# test.sh
echo $@
echo $1
echo $2
echo $3
echo $4
echo $5
exit

Running the command: # ./test.sh -e -f -c -n -g outputs:

-f -c -n -g

-f
-c
-g

./test.sh -n -f -c -e -g outputs:

-f -c -e -g-f
-c

-g

Why do -e and -n not appear in "$@"? -e appears to pass as an empty parameter and -n appears to remove the following endline. Furthermore I noticed that these parameters are accounted for when echoing $#. Does anyone know why -e and -n behave differently than any other parameters.

atw31337
  • 23
  • 2
  • 2
    Another reason to use `printf '%s\n'` instead of `echo`. – chepner Sep 21 '18 at 22:09
  • Hmm. [I just assigned a variable but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) (a reference question intended for this class of problem) doesn't currently cover the case, but it *should*. – Charles Duffy Sep 21 '18 at 22:35

1 Answers1

3

The -e is passed like an argument to echo and then is comsumed by it.

Try this instead :

#!/bin/bash
printf '%s\n' "$1"
printf '%s\n' "$2"
printf '%s\n' "$3"
printf '%s\n' "$4"
printf '%s\n' "$5"

Output :

-e
-f
-c
-n
-g

Check help echo | less +/-e

You can use :

echo -- "$1"

too

Another solution

using bash here document

#!/bin/bash
cat<<EOF
$1
$2
$3
$4
$5
EOF
Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195
  • That makes sense since both -e and -n are echo options. Is there an easy way to remove the leading `--` without piping? – atw31337 Sep 21 '18 at 22:14