Click to See Complete Forum and Search --> : [SOLVED] Bash script arguments


tecknophreak
04-20-2007, 02:57 PM
I'm passing a bash script three arguments. When they are single words, no problem. When they are more than one word, but passed through by me typing them, no problem. The problem comes in when the arguments are created by another script/program:

Test script:
#!/bin/bash

echo $1
echo $2
echo $3

./test "one one" two three
one one
two
three

./test `echo \"one one\" two three`
"one
one"
two

What am I missing here?

knute
04-20-2007, 03:40 PM
./test `echo \"one one\" two three`
./test `echo \"one\ one\" two three`

tecknophreak
04-20-2007, 04:06 PM
Same result. a ./test one\ one two three, appears the same as a ./test "one one" two three, but when using the echo, I still get the
"one
one"
two

bwkaz
04-20-2007, 07:00 PM
Backticks mess that kind of thing up. The parsing rules are ... odd when you use backticks like that.

In particular, the output of the command is not fully re-parsed by the shell before being passed to the next command; quotes do not cause words to be kept together. (Word splitting happens on all whitespace, in other words.) Also, I believe whitespace is collapsed (this won't affect what you're trying to do, but it does change the output of the command between the time it gets printed and the time the command substitution puts it into the parent command).

I don't think it's possible to get the shell to parse the double-quoted string that results from the command as a single word. Any way you do it, the substitution is going to happen too late for the quotes to have any effect.

However, this works on my machine:

$ ( echo \"one one\" ; echo two ; echo three ) | xargs ./test.sh since xargs uses the shell's normal word-parsing rules when splitting arguments to pass to test.sh (because xargs actually runs another shell). (But note that xargs is geared more toward filenames; if the total command line length is too long, it will run test.sh twice, or more.) Normally xargs isn't a good idea if the source data can have newlines in it, either, but I don't know whether that's a concern or not. (Normally xargs treats each line of input as a separate argument. The quotes are there so the string that xargs generates to send to the shell has them in it.)

tecknophreak
04-22-2007, 04:29 PM
Perfect!! I have another program which outputs three strings, none with newlines in them. So instead of outputting all on one line, they can have a line each and this'll work.

Thank!