2

The following command with 2 parameters does what I need if I enter it in a terminal:

mycommand 'string that includes many spaces and double quotes' 'another string that includes many spaces and double quotes'

Now I move the above to the bash script.

C=mycommand 'string that includes many spaces and double quotes'
function f {
 $C $1
}
# let's call it
f 'another string that includes many spaces and double quotes'

Obviously this is not going to produce the same result, or any useful result. But I can not come up with the correct way of preserving and/or properly escaping quotes, spaces and keeping number of actual parameters that mycommand sees as 2.

I use GNU bash version 3.2.57 on a Mac.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Dmitry
  • 21

1 Answers1

1

If you quote each parameter, it will be properly handled as a positional parameter:

#!/usr/local/bin/bash
f() {
  echo "function was called with $# parameters:"
  while ! [[ -z $1 ]]; do
    echo "  '$1'"
    shift
  done
}
f "param 1" "param 2" "a third parameter"
$ ./459461.sh
function was called with 3 parameters:
  'param 1'
  'param 2'
  'a third parameter'

Note however that the containing (i. e. outermost) quotes are not part of the parameter itself. Let's try a slightly different invocation of the function:

$ tail -n1 459461.sh
f "them's fightin' words" '"Holy moly," I shouted.'
$ ./459461.sh
function was called with 2 parameters:
  'them's fightin' words'
  '"Holy moly," I shouted.'

Observe that the 's in the output surrounding the reproduced parameters are coming from the echo statement in the function, and not the parameters themselves.

To dress up your example code to be more quote-aware, we can do this:

C=mycommand
f() {
  $C "unchanging first parameter" "$1"
}
# let's call it
f 'another string that includes many spaces and double quotes'

Or this:

C=mycommand
f() {
  $C "$1" "$2"
}
# let's call it
f 'Some string with "quotes" that are scary' 'some other "long" string'
DopeGhoti
  • 76,081