You are not logged in.

#1 2020-12-19 13:02:53

risto3
Member
Registered: 2016-09-27
Posts: 32

recent bash difficulties using ····`test`

Maybe it's never been great bash scripting, but I've most often used `test` explicitly for what seems to provide better readability,
but since recently(since bash 5.1?) some of my scripts no longer work...

For example, something like the following (greatly simplified):
  if test $(hg summary | grep -q heads); then echo 'rebase needed'; fi

doesn't work anymore

but simply
  if $(hg summary | grep -q heads); then echo 'rebase needed'; fi
does.

Is this a lesson in fixing bad scripts or perhaps a new bug?

Offline

#2 2020-12-19 13:19:08

ayekat
Member
Registered: 2011-01-17
Posts: 1,460
Website

Re: recent bash difficulties using ····`test`

risto3 wrote:

if test $(hg summary | grep -q heads)

Unless that command between $(…) produces a valid sequence of strings that can be passed as arguments to test, that has never been valid bash (or sh in general) scripting. And IMHO it doesn't help readability at all (at least for someone knowing shell scripting…)

From what I can see, that will actually never do the `then` part, because `grep -q` will not output anything, and so no argument is passed to `test`, resulting in it always exiting with a non-zero return code.

I believe you wanted this instead:

if hg summary | grep -q heads; then …

{,META,RE}PKGBUILDSpacman-hacks (includes makemetapkg and remakepkg) │ dotfiles

Offline

#3 2020-12-19 15:57:25

risto3
Member
Registered: 2016-09-27
Posts: 32

Re: recent bash difficulties using ····`test`

yeah, cockpit error... thx

Offline

#4 2020-12-30 23:00:56

solskog
Member
Registered: 2020-09-05
Posts: 306

Re: recent bash difficulties using ····`test`

# hg summary | grep -q heads && { echo "rebase"; }

Same result, less typing maybe.

Offline

#5 2020-12-31 07:18:13

ayekat
Member
Registered: 2011-01-17
Posts: 1,460
Website

Re: recent bash difficulties using ····`test`

No need for the curly braces, even:

hg summary | grep -q heads && echo rebase

But generally, I would recommend not doing any such code golfing unless it helps readability.


{,META,RE}PKGBUILDSpacman-hacks (includes makemetapkg and remakepkg) │ dotfiles

Offline

Board footer

Powered by FluxBB