0

I'm running this command in jenkins, and it's using sh. However I'm not sure what this error means in my bash script

#! /bin/sh
for d in $(ls -d kube/xx/bb/!(abc*|!cdf*)/ | xargs -I {} basename {} ) ;do echo $d; done
test.sh: command substitution: line 3: syntax error near unexpected
token `(' test.sh: command substitution: line 3:
`ls -d kube/xx/bb/!(abc*|!cdf*)/ | xargs -I {} basename {} )'
Quasímodo
  • 18,865
  • 4
  • 36
  • 73
Swat
  • 177

1 Answers1

3

You're trying to use an extended globbing pattern in a script running under /bin/sh, which is a shell that generally does not understand those sorts of patterns.

Either switch to a shell that know about these patterns, like bash, ksh, or zsh (with the appropriate options set in each shell), or use something that /bin/sh would understand, such as find:

#!/bin/sh

find kube/xx/bb -prune ! -name 'abc' ! -name 'cdf' -type d -exec basename {} ;

Or, if you're using GNU find:

#!/bin/sh

find kube/xx/bb -prune ! -name 'abc' ! -name 'cdf' -type d -printf '%f\n'

In both of these examples, I'm assuming that the ! in front of cdf* in the question is a typo.

Note that there is rarely a need to run xargs in a pipeline with find as find has a perfectly usable -exec predicate for executing arbitrarily complex commands.

Also, Why *not* parse `ls` (and what to do instead)?


A more manual approach:

#!/bin/sh

for pathname in kube/xx/bb/*/; do [ -d "$pathname" ] || continue

name=${pathname%/}
name=${name#kube/xx/bb/}

case $name in
    abc*|cdf*) continue ;;
esac

printf '%s\n' "$name"

done

Kusalananda
  • 333,661