0

Can someone explain why stat is interpreting its format string (except the first format sequence) as whitespace-delimited input parameters when passed as a variable to xargs?

$ v="stat -c \"%8i %A\""; echo $v; echo /bin/ls | xargs -t $v
stat -c "%8i %A"
stat -c "%8i %A" /bin/ls
stat: cannot stat '%A"': No such file or directory
dfernan
  • 377
  • 2
  • 9
  • 22
  • 3
    http://mywiki.wooledge.org/BashFAQ/050#I.27m_trying_to_put_a_command_in_a_variable.2C_but_the_complex_cases_always_fail.21 – that other guy Oct 27 '16 at 20:23
  • 2
    I'd link to one of the many duplicates, but a large number of them have atrociously bad answers (often suggesting `eval`). [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) is indeed probably the best guide on this particular subject. And read [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048) before doing anything with `eval`. – Charles Duffy Oct 27 '16 at 20:32
  • 2
    BTW, `xargs` has some design bugs that will bite you with this usage pattern. Do note how it treats whitespace, literal backslashes, &c. in its input; in general, it's only safe to use with arbitrary filenames in conjunction with a NUL-delimited input stream and the `-0` argument (a non-POSIX extension, but available on both BSD and GNU systems). Also related: [ParsingLs](http://mywiki.wooledge.org/ParsingLs). Consider using GNU `find` with `-print0` -- though really, you can use `find -printf` to do the work of `stat` as well. – Charles Duffy Oct 27 '16 at 20:36
  • So getting the posted code running is not possible, right (due to word splitting without double-quoting the variable for expansion, which cannot be made due to `xargs`)? – dfernan Oct 27 '16 at 21:05
  • 1
    @dfernan, depends on what you mean by "the posted code". If you changed it to use arrays, for instance, you'd have something more like the following: `v=( stat -c "%8i %A" ); printf '%q ' "${v[@]}"; echo; echo /bin/ls | xargs -t "${v[@]}"` – Charles Duffy Oct 28 '16 at 01:49
  • @dfernan, ...I'm certainly not going to say that there aren't any ways you could use a string, but I *am* going to say that those ways are all bad practice and things that you shouldn't do without a very compelling reason. – Charles Duffy Oct 28 '16 at 01:50
  • @CharlesDuffy, the solution with the array works. I now start to better understand the importance of the whitespace. Thanks! – dfernan Oct 28 '16 at 07:36

0 Answers0