0

So I have a function I'd like to unpack an array of params to form the argument sequence:

#!/usr/bin/env bash

my_func() {
    echo "IN LEN: $#"  # Gives "6" -> Should be "4"
    echo "IN: $@"  # Gives "--a 1 --b 2 3 4" -> Should be "--a 1 --b 2\n3\n4"
}


read -r -d '' MULTI << EOM
2
3
4
EOM

ARGS=("--a" "1" "--b" "$MULTI")
echo "OUT LEN: ${#ARGS[@]}"  # 4
echo "OUT: ${ARGS[@]}"  # "--a 1 --b 2\n3\n4"

my_func ${ARGS[@]}

This example demonstrates the issue and what I'm expecting. Maybe some magic with setting IFS? Any suggestions?

PS. See my original question if you need some more context: Handle optional function arguments

Community
  • 1
  • 1
Alex Latchford
  • 655
  • 1
  • 9
  • 17
  • 1
    You need double quotes around the argument: `my_func "${ARGS[@]}"` – codeforester Mar 17 '17 at 17:58
  • Easy! Man tried so many variants must have just missed this one! – Alex Latchford Mar 17 '17 at 18:02
  • 1
    You missed the one that provides the entire rationale for having two different symbols `*` and `@` as a means of expanding to all the elements of an array. Always, always, always, *always* quote parameter expansions. – chepner Mar 17 '17 at 18:12
  • 1
    BTW, http://shellcheck.net/ would have caught this for you. – Charles Duffy Mar 17 '17 at 18:22
  • As an aside, see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html -- POSIX specifies that all-caps names are to be used for variables with meaning to the operating system and shell, and reserves lowercase names for application use; following this convention avoids overwriting meaningful names by mistake, and makes it easier for a reader to tell when you're defining a name for your own purposes, vs for its side effects on other tools. (This convention applies to shell variables as well as environment variables, as setting the former will overwrite the latter on conflict). – Charles Duffy Mar 17 '17 at 18:23

1 Answers1

5

Change my_func ${ARGS[@]} to my_func "${ARGS[@]}"

Without the enclosing double quotes, the arguments get expanded and shell removes the trailing new lines.

sjsam
  • 21,411
  • 5
  • 55
  • 102
Shridhar.S
  • 112
  • 2
  • Well, it is a bit surprising that the op who put the quotes around `$MULTI` when adding it to array forgot to do so when they called the function.. Anyways, this solves the problem. – sjsam Mar 17 '17 at 18:20