How to preserve white space in Bash arguments

3

I use the command:

cm1 cm2 arg1 arg2 'argument 3'

It first goes to cm1, which will then redirect arg1 arg2 'argument 3' to another file.

/usr/bin/cm1:

#! /bin/bash
# some script here
shift
cm2 $@

/usr/bin/cm2:

echo $#
# This returns 4 in lieu of 3 because the white space in 'argument 3' causes the argument to be split into two arguments.

So, how can I pass arguments from one script to another and make sure white space won't be read as an argument separator?

François ッ Vespa ت

Posted 2012-03-13T10:24:12.793

Reputation: 137

Answers

5

I assume you have to re-wrap it into quotes, like so:

#! /bin/bash
# some script here
shift
cm2 "$@"

Der Hochstapler

Posted 2012-03-13T10:24:12.793

Reputation: 77 228

I was looking for opposite behavior - how to force my script to iterate over arguments separated with spaces. In my script I had quoted reference ("$@") so all arguments were treated as one concatenated string. I replaced: >for path in "$@"< with: >for path in $@< and it worked. Thank you. – mombip – 2018-11-07T11:23:47.083

Thanks! It works on the simple example I gave. Now on the real script I am coding and that has more complex rerouting, arguments get broken at some point. But that means the error is coming from somewhere else... Thanks! – François ッ Vespa ت – 2012-03-13T10:30:25.483

It may be that you split these args later based on default IFS which default value is "<space><tab><newline>" – Cougar – 2012-03-14T09:48:12.293