Linux scripting parsing multiple arguments to a function mixed with words and quoted sentences

Viewed 31

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.

1 Answers

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[@]}"
Related