1
~$> function f { local opt; read -p "choose from args [ $@ ]:" opt; }
~$> f a b
-bash: read: `b ]:': not a valid identifier

The workaround I employed was

echo -ne "choose from args [ $@ ]:"; read opt;
           OR
local args="$@"
read -p "choose from args [ ${args} ]:" opt;

But can someone explain why it does not work with read -p .

Note: read -p "choose from args [ $1 ]:" seems to work just fine. Using Platform Cygwin and debian 9. bash version 4.4.12 and 5.0.3.

hardeep
  • 186
  • 1
  • 7

1 Answers1

4

When there are multiple arguments $@ expands to multiple words. It's as if you'd written:

read -p "choose from args[ a" "b ]:" opt

It sees "b ]:" as a separate argument not belonging to -p, interprets it as a variable name, and then declares that b ]: is not a valid identifier.

Use $* to ensure the arguments are always expanded as a single string.

read -p "choose from args [ $* ]:" opt
John Kugelman
  • 349,597
  • 67
  • 533
  • 578