I'm encountering an issue passing an argument to a command in a Bash script.

poc.sh:

#!/bin/bash

ARGS='"hi there" test'
./swap ${ARGS}

swap:

#!/bin/sh
echo "${2}" "${1}"

The current output is:

there" "hi

Changing only poc.sh (as I believe swap does what I want it to correctly), how do I get poc.sh to pass "hi there" and test as two arguments, with "hi there" having no quotes around it?

share|improve this question
    
This is the topic of BashFAQ #50: mywiki.wooledge.org/BashFAQ/050 – Charles Duffy Sep 26 '14 at 21:22

A Few Introductory Words

If at all possible, don't use shell-quoted strings as an input format.

  • It's hard to parse consistently: Different shells have different extensions, and different non-shell implementations implement different subsets (see the deltas between shlex and xargs below).
  • It's hard to programatically generate. ksh and bash have printf '%q', which will generate a shell-quoted string with contents of an arbitrary variable, but no equilavent exists to this in the POSIX sh standard.
  • It's easy to parse badly. Many folks consuming this format use eval, which has substantial security concerns.

NUL-delimited streams are a far better practice, as they can accurately represent any possible shell array or argument list with no ambiguity whatsoever.


xargs, with bashisms

If you're getting your argument list from a human-generated input source using shell quoting, you might consider using xargs to parse it. Consider:

array=( )
while IFS= read -r -d ''; do
  array+=( "$REPLY" )
done < <(xargs printf '%s\0' <<<"$ARGS")

swap "${array[@]}"

...will put the parsed content of $ARGS into the array array. If you wanted to read from a file instead, substitute <filename for <<<"$ARGS".


xargs, POSIX-compliant

If you're trying to write code compliant with POSIX sh, this gets trickier. (I'm going to assume file input here for reduced complexity):

# This does not work with entries containing literal newlines; you need bash for that.
run_with_args() {
  while IFS= read -r entry; do
    set -- "$@" "$entry"
  done
  "$@"
}
xargs printf '%s\n' <argfile | run_with_args ./swap

These approaches are safer than running xargs ./swap <argfile inasmuch as it will throw an error if there are more or longer arguments than can be accommodated, rather than running excess arguments as separate commands.


Python shlex -- rather than xargs -- with bashisms

If you need more accurate POSIX sh parsing than xargs implements, consider using the Python shlex module instead:

shlex_split() {
  python -c '
import shlex, sys
for item in shlex.split(sys.stdin.read()):
    sys.stdout.write(item + "\0")
'
}
while IFS= read -r -d ''; do
  array+=( "$REPLY" )
done < <(shlex_split <<<"$ARGS")
share|improve this answer
    
This doesn't seem to work with ARGS="\"a\\\"b\" c"? Error reported xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option – Cyker Dec 25 '16 at 22:03
    
Fair point -- xargs indeed doesn't honor POSIX sh behavior in that case. Updating with an alternative using the Python 2's shlex.split() function instead. – Charles Duffy Dec 26 '16 at 18:51
    
The best thing to do would be to put the OP back on the right track: if OP needs such a thing, then their design is obviously wrong. Unless OP is writing a shell (or a cli), in which case the choice of language is wrong. Either way, OP is doing it wrong. – gniourf_gniourf Dec 26 '16 at 19:03
    
@gniourf_gniourf, ...in theory, I agree. In practice, folks tend to be given requirements that don't make sense (or need compatibility with longstanding systems/practices -- there are a ton of legacy startup scripts for Java apps floating around that rely on evaling argument lists given in shell-quoted form), and there's value in being able to make the best of a bad situation... though certainly, "don't do that" ought to be part of the advice given. – Charles Duffy Dec 26 '16 at 19:06
1  
@gniourf_gniourf, ...I've edited in an appropriate introduction. – Charles Duffy Dec 26 '16 at 19:09

Embedded quotes do not protect whitespace; they are treated literally. Use an array in bash:

args=( "hi there" test)
./swap "${args[@]}"

In POSIX shell, you are stuck using eval (which is why most shells support arrays).

args='"hi there" test'
eval "./swap $args"

As usual, be very sure you know the contents of $args and understand how the resulting string will be parsed before using eval.

share|improve this answer
1  
I would tend to argue that there are more options that eval here. Even in POSIX, one could read into "$@" from xargs. – Charles Duffy Jul 17 '15 at 23:07

This might not be the most robust approach, but it is simple, and seems to work for your case:

## demonstration matching the question
$ ( ARGS='"hi there" test' ; ./swap ${ARGS} )
there" "hi

## simple solution, using 'xargs'
$ ( ARGS='"hi there" test' ; echo ${ARGS} |xargs ./swap )
test hi there
share|improve this answer
    
Commentary: Bash string processing is extremely confusing. xargs removes the guesswork by passing parameters directly via exec, which bypasses the normal, capricious, string processing that Bash would otherwise perform as part of string-based command-line processing. – nobar Apr 1 '17 at 18:13
    
I can't be sure about my assertion regarding exec. But I stand by my statement that "Bash string processing is extremely confusing". – nobar Apr 1 '17 at 18:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.