Friday, October 7, 2022

[SOLVED] Bash "-n" argument not recognized by script when using "$@"

Issue

I am using a bash script that expects command line arguments preceded by a dash followed by a file name:

./script -abc file_name

In the script, I try to print out all of the arguments to the script using:

echo "$@"

which displays:

-abc file_name

which is expected. Everything prints fine except for when I use the letter "n" by itself, i.e.:

./script -n file_name

The resulting echo statement inside the script only prints out the file_name argument and not the "-n" argument at all. This behavior only occurs with the letter "n" by itself. When I try "-nx" or 'n' with any other letter(s) the echo statement prints out fine...

Why does this echo statement not work with "-n" by itself?


Solution

The -n or -e are valid options for the echo command.

Therefore it's consumed by the echo command and only the remaining text is shown.
That's a known problem of echo and to avoid this you can use printf.

printf "%s\n" "$*"


Answered By - jeb
Answer Checked By - Cary Denson (WPSolving Admin)