扩展字符串变量中的通配符
expand wildcards in string variable
我正在从包含应删除的文件和文件夹的黑名单文件中读取字符串。它适用于简单的文件名,但不适用于通配符。
例如如果我在 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 )
我怎样才能让它工作?
最有可能的是,extglob
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
你必须
- 打开
extglob
shell 选项
- 使用
$line
不加引号:引用会抑制 glob 扩展,几乎总是 需要,但这里不是
注意我使用小写变量名。大写保留用于 shell 和环境变量;使用小写字母可以减少名称冲突的可能性(参见 POSIX spec,第四段)。
此外,这里不需要eval
。
我正在从包含应删除的文件和文件夹的黑名单文件中读取字符串。它适用于简单的文件名,但不适用于通配符。
例如如果我在 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 )
我怎样才能让它工作?
最有可能的是,extglob
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
你必须
- 打开
extglob
shell 选项 - 使用
$line
不加引号:引用会抑制 glob 扩展,几乎总是 需要,但这里不是
注意我使用小写变量名。大写保留用于 shell 和环境变量;使用小写字母可以减少名称冲突的可能性(参见 POSIX spec,第四段)。
此外,这里不需要eval
。