user3150128
user3150128

Reputation: 455

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?

Upvotes: 3

Views: 4277

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52112

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.

Upvotes: 5

Related Questions