0

I was trying to parse multiple arguments to a function but its not recognising the 2nd argument as a sentence since it's quoted. How can I make the following work like I want:

test.sh:

#!/bin/sh

print ()
{
  echo $1
  echo $2
}

sentence="this is foo bar"
test="foo, \"${sentence}\""
print ${test}

Outputs:

foo,
"this

Expected Output:

foo,
this is foo bar

Appreciate, any help I can get.

aynber
  • 22,380
  • 8
  • 50
  • 63
Langerz
  • 71
  • 1
  • 5
  • I think you're looking for `eval print "${test}"`. – larsks Sep 22 '22 at 03:16
  • OMG!! It worked perfect thank you so much! I was pulling my hair out trying to make it work!! – Langerz Sep 22 '22 at 03:28
  • 1
    Ack! Avoid `eval` if at all possible, it is a massive bug magnet. Don't put quotes in variables; variables are for storing data, but quotes and escapes are shell syntax, not data. *Do* [put double-quotes around variable references](https://stackoverflow.com/questions/55023461/when-should-i-double-quote-a-parameter-expansion). If you really need to store multiple items (like multiple arguments) in a single variable, [use an array rather than a plain variable](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia). – Gordon Davisson Sep 22 '22 at 07:47

1 Answers1

0

To make it work correctly I will pass the print arguments as an array and then access values with their indexes:

#!/usr/bin/env bash

print ()
{
    args=("$@")
    echo "${args[0]}"
    echo "${args[1]}"
}

sentence="this is foo bar"
test=(foo, "$sentence")                                                                                                                                                                                            
print "${test[@]}"
Martin Tovmassian
  • 1,010
  • 1
  • 10
  • 19