gpt4 book ai didi

bash - 扩展字符串变量中的通配符

转载 作者:行者123 更新时间:2023-11-29 09:22:50 25 4
gpt4 key购买 nike

我正在从包含应删除的文件和文件夹的黑名单文件中读取字符串。它适用于简单的文件名,但不适用于通配符。

例如如果我在 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 )

我怎样才能让它工作?

最佳答案

最有可能的是,非交互式 shell 的 extglob 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

关于bash - 扩展字符串变量中的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com