Passing -e and -n as positional parameters in Bash

49 views Asked by At

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.

1

There are 1 answers

1
Gilles Quénot On BEST ANSWER

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