0

Executing this command gives the expected output - the "c d" is handled as a single argument:

% /bin/sh -c 'args="$@"; for a in "$@"; do echo $a; done' -- a b "c d"
a
b
c d

If the same argument is stored in a file and passed to script by cat, I got the undesired output - the "c d" is handled as 2 arguments:

% echo a b \"c d\" > foo
% cat foo
a b "c d"
% /bin/sh -c 'args="$@"; for a in "$@"; do echo $a; done' -- `cat foo`
a
b
"c
d"

Is there any way to make the argument passed as result of command execution be handled as it were passed as a string?

Tks

Walter X
  • 11
  • 4
  • http://mywiki.wooledge.org/BashFAQ/050 – Charles Duffy Jul 17 '15 at 22:58
  • One can also use xargs here -- in its less-safe usage modes it'll do shell-like parsing. Consider: `array=( ); while IFS= read -r -d ''; do array+=( "$REPLY" ); done < <(xargs printf '%s\0' – Charles Duffy Jul 17 '15 at 23:01
  • "As if it were passed as a string", by the way, isn't very meaningful: Strings are parsed differently depending on at which expansion phase they're handled. That's the immediate cause of your problem here: A string that occurs as an expansion result happens after syntactic parsing (for things like quotes) has already taken place. That's a good thing -- it would be impossible to write code in shell that securely handled untrusted data otherwise. – Charles Duffy Jul 17 '15 at 23:05
  • Nice tips, using NUL ('\0') as a separartor is clever. In case of some shells where `read` ignores NUL [(Bash 4.3-alpha)](http://wiki.bash-hackers.org/commands/builtin/read), is there any other separator that can be safely used? – Walter X Jul 19 '15 at 00:46
  • And just for curiosity, any reason for using `$REPLY` instead of an `array` var along with `read -a array`? Tks – Walter X Jul 19 '15 at 00:51
  • `read -a` uses delimiters from IFS; one can't store NULs in a scalar variable such as IFS. As for your bash-hackers link -- you're misreading the behavior described; NULs within input records are skipped, but NUL delimiters between records (specified with `-d ''`) are still honored. The practice of using `IFS= read -r -d ''` is well-established -- found in http://mywiki.wooledge.org/BashFAQ/001, for instance; any change which broke it would never make it to release. – Charles Duffy Jul 19 '15 at 04:44
  • Beyond that -- it's the fact that NUL can't be stored inside of a C string is what makes it safe to use. As NUL is the only character which terminates a C string, it's unique in that respect. – Charles Duffy Jul 19 '15 at 04:46
  • Right, now the reasons why using NUL and not using `read -a` are clear. Tks – Walter X Jul 20 '15 at 14:50

0 Answers0