0

So I am trying to pass variable arguments to a bash function. Here is what my code looks like

function log_output(){

  args=("$@")

  for statement in ${args}
  do
    echo "${statement}"
  done
}

When I make the following call log_output "hello bye" I expect the function to print hello bye in one line. However currently its printing it in two different lines. Why is the string "hello bye" being treated as two arguments by the function? What am I doing wrong?

Much appreciated!

Abdul Rahman
  • 1,294
  • 22
  • 41
  • 1
    `for statement in "${args[@]}"`; `${args}` only expands to the first element in the array (and then, because it isn't correctly quoted, string-splits it on characters in IFS and expands each resulting word as a glob). – Charles Duffy Sep 25 '19 at 20:10
  • 1
    BTW, `function foo() {` is a hybrid of legacy-ksh and POSIX sh function definition syntax forms that isn't compatible with *either* legacy ksh *or* POSIX sh. Use either (worse) `function foo {` -- which is the legacy ksh form -- or (better) `foo() {` with no `function`, which is the POSIX-compliant form. See also https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Sep 25 '19 at 20:12
  • 1
    Also, consider making a habit of running your code through http://shellcheck.net/ and fixing issues it identifies before asking questions here. In this specific case, it would have given you the warning SC2128, explained in detail [in this wiki page](https://github.com/koalaman/shellcheck/wiki/SC2128). – Charles Duffy Sep 25 '19 at 20:14
  • @CharlesDuffy Much appreciated! – Abdul Rahman Sep 25 '19 at 20:27

0 Answers0