Reputation: 43872
I have a string that contains something like this:
apple orange pear grapes
And I have a command that works like this:
eat food [additionalFood [additionalFood [additionalFood...]]
If I do eat $s
, then it will treat the whole string as one big food. How can I break up the string into passable arguments?
Upvotes: 1
Views: 3868
Reputation: 17654
If eat
is not your direct script, use set
. try help set
in your terminal
set
: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...] Set or unset values of shell options and positional parameters.
example:
$ allargs="foo bar baz"
$ set -- $allargs # notice no quoting here
$ echo "$1" # foo
$ echo "$2" # bar
$ echo "$3" # baz
If eat
is the direct script, then $1
$2
are alread set for you, unless your arguments are quoted
$ eat foo bar baz
## then "$1" is foo, "$2" is bar etc
$ eat "foo bar baz" # quoted arguments
## then "$1" is "foo bar baz"
More options would include a for
loop, see @Oli Charlesworth answer,
or even an array:
$ arr=($allargs) # allargs as defined above, also no quoting
$ echo "${arr[0]}" # foo
$ echo "${arr[1]}" # bar
etc
Upvotes: 1
Reputation: 272667
It shouldn't treat that as one big string. Example:
test.sh
#! /bin/bash
for stuff; do
echo "XXX: $stuff"
done
Command-line
chmod +x test.sh
s="apple orange pear grapes"
./test.sh $s
Output
XXX: apple
XXX: orange
XXX: pear
XXX: grapes
If this isn't working for you, it's possible your IFS
variable is set to a non-default value.
Upvotes: 4