0

I have a function in my shell script that takes options. It works fine, until I try to pass '-n' option, then the function cannot read the arg.

func ()
{
for arg in "$@"
do
echo $arg
done
}

func -p #works
func -e #works
func -n #doesn't work, func cannot read arg

Anyone has an idea of why this is happening?

Tried: passing multiple options to the function, they all work, except '-n'. Expect: read '-n' as an argument in my function.

2 Answers2

0

The way you pass the arguments to echo make them be considered echo's switches and since -n is a valid switch (BTW -e is also valid switch on my echo you would be lucky just with -p here). is not being echoed. If you want to print them using echo you can try adding -- to signal end of arguments, so $arg won't be interpreted as such (echo -- $arg) but that also may depend on the shell you are using.

EDIT: as support for -- is not default, you may want to replace echo with printf:

printf "%s\n" "${arg}"
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • Using `--` doesn’t work on my default macOS bash (`echo -- $arg` prints `-- -n`). – Nicolapps Nov 25 '22 at 06:56
  • `echo -- $arg` does not work. using `printf` solved the issue. – Vinicius Gonçalves Melo Nov 25 '22 at 07:06
  • I'm running `#!/bin/sh` script from a Debian system. – Vinicius Gonçalves Melo Nov 25 '22 at 07:07
  • side note: `/bin/sh` is usually symlink to `bash`, `dash` or any other more modern shell than `sh`. – Marcin Orlowski Nov 25 '22 at 07:11
  • Yes, just checked it's a symlink to `dash` on Debian bookworm. Thanks for the answer (do not have enough reputation to cast a vote...). – Vinicius Gonçalves Melo Nov 25 '22 at 07:23
  • "More modern" is not entirely accurate. Ideally `/bin/sh` should be a POSIX `sh` but in practice this is only more or less true. Which shell exactly tries to implement this is, by definition, an implementation detail; but you should not try to use non-POSIX features in portable `sh` scripts. If it's for your local use only, of course, you can cut corners if you know exactly how your `/bin/sh` deviates from POSIX. – tripleee Nov 25 '22 at 07:26
0

-n might be interpreted as an option for the echo command. To avoid this, use printf instead:

printf '%s\n' "$arg"
Nicolapps
  • 819
  • 13
  • 29