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?
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
extglob shell option$line unquoted: quoting suppresses glob expansion, which is almost always desired, but not hereNotice 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With