Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expand wildcards in string variable

I'm reading strings from a blacklist file which contains files and folders which should get deleted. It works for simple file names, but not with wildcards.

E.g. if I type on the shell rm -rf !(abc|def) it deletes all but these two files. When putting this string !(abc|def) into blacklist it does not work, because the string does not get evaluated.

So I tried to use eval, but it does not work as expected.

#!/bin/bash
# test pattern (normally read from blacklist file)
LINE="!(abc|def)"

# output string
echo "$LINE"

# try to expand this wildcards
eval "ls $LINE"

# try with subshell
( ls $LINE )

How can I make this working?

like image 778
user3150128 Avatar asked Aug 02 '26 00:08

user3150128


1 Answers

Most likely, the extglob shell option is turned off for non-interactive shells (like the one your script runs in).

You have to change a few things:

#!/bin/bash

# Turn on extglob shell option
shopt -s extglob

line='!(abc|def)'

echo "$line"

# Quoting suppresses glob expansion; this will not work
ls "$line"

# Unquoted: works!
ls $line

You have to

  • turn on the extglob shell option
  • use $line unquoted: quoting suppresses glob expansion, which is almost always desired, but not here

Notice that I use lowercase variable names. Uppercase is reserved for shell and environment variables; using lowercase reduces the probability of name clashes (see the POSIX spec, fourth paragraph).

Also, eval is not needed here.

like image 105
Benjamin W. Avatar answered Aug 03 '26 20:08

Benjamin W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!