aguadopd
aguadopd

Reputation: 581

Bash expansion: Different results when running file or running in terminal // extglob

In some script I want to use the name of the folders inside the current folder. I want to get folder names, and I will only put the problematic part in an example here. If I run this from the terminal, I get:

$ for D in */; do echo ${D%%+(/)} ; done
galaxya8
iphone6s
motog6
motog7

$ echo ${0}
/bin/bash

$ bash --version
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

However, if I put that into a file and run the file I get names with trailing slashes:

$ echo 'for D in */; do echo ${D%%+(/)} ; done' >> test.sh

$ bash test.sh
galaxya8/
iphone6s/
motog6/
motog7/

I saw that bash expansion here. What am I missing? Maybe some default value for interactive shells only?


Minimal, complete and verifiable example (Thanks @kamil-cuk):

$ D=a/; echo ${D%%+(/)}; bash <<<'D=a/; echo ${D%%+(/)}'
a
a/

Upvotes: 1

Views: 81

Answers (1)

KamilCuk
KamilCuk

Reputation: 141145

From the bash manual:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. ...

+(pattern-list)
Matches one or more occurrences of the given patterns.

You need enable extglob shopt option in your script to use extended pattern matching operator the +(/).

echo 'shopt -s extglob; for D in */; do echo ${D%%+(/)} ; done' > test.sh

Upvotes: 5

Related Questions