Home > Enterprise >  How to control when glob is expanded, pass glob into bash script from sh and then expand it
How to control when glob is expanded, pass glob into bash script from sh and then expand it

Time:08-06

I am trying to run some code in a CI system

Bash 5 is available but the initial command is run from sh

I think I need bash features

This prints literal **/*.json:

bash -c 'echo **/*.json'

This works:

bash -c 'shopt -s globstar; echo **/*.json'

This gives "syntax error near unexpected token `('":

bash -c 'shopt -s extglob; echo **/*.@(yml|yaml)'

I found this answer which suggests the reason for the syntax error https://stackoverflow.com/a/49283991/202168

i.e. globstar is fine in a one-liner but the same doesn't work for extglob because blah blah something to do with the parser.

So I tried creating a wrapper script:

#!/usr/bin/env bash

shopt -s globstar
shopt -s extglob

exec "$@"

And to call it:

wrapper.sh 'echo **/*.@(yml|yaml)'

but it seems as if the glob is not expanded, I get "No such file or directory".

Alternatively:

wrapper.sh echo '**/*.@(yml|yaml)'

just echoes literal **/*.@(yml|yaml)

And:

wrapper.sh echo **/*.@(yml|yaml)

gives "syntax error" again, I assume because now the sh is trying to parse the glob part before it gets to the bash wrapper.

How do I pass the glob into the wrapper script so that it is expanded in the bash wrapper before calling echo?

(I am looking for solutions to this, not for alternative ways to list yml or yaml files)

CodePudding user response:

This should work (the reason is explained in the answer you found):

bash -c 'shopt -s extglob globstar
echo **/*.@(yml|yaml)'

Please note the literal newline character, instead of ;, inside single quoted command string.

CodePudding user response:

You may use bash here-doc like this:

bash -s <<-'EOF'
shopt -s extglob globstar
echo **/*.@(yml|yaml)
EOF
  • Related