[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: shellcheck, bashism's and one liners.



On Sun, Mar 17, 2024 at 10:57:43AM -0500, Nate Bargmann wrote:
> What errors do you get if you use sh instead of bash?

He's not getting any errors.  His script actually works for his current
inputs.  He was just getting warnings from shellcheck, which is an
external script validation tool.

One of the warnings is harmless in this context.  He's doing something
that *looks* like a common newbie mistake, but actually isn't, and the
reason he's doing it is out of his control (design of apt-get).

The other warning is a valid one, because what he's doing won't work
in the general case, where filenames contain whitespace or globbing
characters.  It works fine with "naive" filenames (alphanumeric plus
a very limited set of punctuation, such as . _ - characters), but
doesn't generalize.


On Sun, Mar 17, 2024 at 11:14:56PM +0700, Max Nikulin wrote:
> On 17/03/2024 16:25, Tim Woodall wrote:
> > args() { echo a b c d; }
> > count() { echo $#; }
> > count $(args)
> 
> args() { printf '%s\0' a b c d; }
> args | xargs -0 sh -c 'count() { echo $#; }; count "$@"' sh-count
> 
> It would be easier in the case of script file instead of shell function. An
> assumption is that all arguments may be passed through command line.

Tim's assumption here is that he can write a function which emits a
stream of whitespace-separated words, and use this safely in an unquoted
command substitution.

    count $(args)

I'm guessing "count" is a stand-in for something more complex, but $(args)
is pretty much exactly what he wants to do in his real script.

The problem is that this works *brilliantly* with inputs that are
heavily restricted to a specific set of characters, and fails *utterly*
if the inputs do not conform to that limitation.  There is no middle
ground, and there is no way to fix it up.  Once your inputs take off
their training wheels, you have to throw this script away and rewrite
it from the ground up.

That's why shellcheck gives warnings about this kind of thing.  (Well,
one of many reasons.)


Reply to: