use*_*128 3 bash wildcard expansion
我正在从黑名单文件中读取字符串,其中包含应删除的文件和文件夹.它适用于简单文件名,但不适用于通配符.
例如,如果我在shell上键入,rm -rf !(abc|def)它将删除除这两个文件之外的所有文件.将此字符串!(abc|def)放入黑名单时,它不起作用,因为字符串不会被评估.
所以我尝试使用eval,但它没有按预期工作.
#!/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 )
Run Code Online (Sandbox Code Playgroud)
我怎样才能使这个工作?
最有可能的extglob是,对于非交互式shell(如脚本运行的shell),关闭shell选项.
你必须改变一些事情:
#!/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
Run Code Online (Sandbox Code Playgroud)
你必须
extglobshell选项$lineunquoted:quoting抑制glob扩展,这几乎总是需要,但不是在这里请注意,我使用小写变量名称.大写是为shell和环境变量保留的; 使用小写可以减少名称冲突的可能性(参见POSIX规范,第四段).
此外,eval这里不需要.