【问题标题】:Why does the pattern *([^\/]) work in my interactive shell but not a script? [duplicate]为什么模式 *([^\/]) 在我的交互式 shell 中有效,但在脚本中无效? [复制]
【发布时间】:2014-11-04 01:24:02
【问题描述】:

我正在编写一个脚本来使用 bash 参数替换将工作目录剥离到有限的长度。它适用于命令行,但相同的替换在脚本中没有任何作用。

代码:

#!/bin/bash

# Limit of working directory length
LIMIT=10

dir=${1/#$HOME/\~}

# If it's too long, normalize it by stripping ~ and adding ...
if [ ${#dir} -gt $LIMIT ]; then
  dir=${dir/#\~/"..."}
fi

echo $dir

# Strip levels until short enough or can't strip anymore.
while [[ ( ${#dir} -gt $LIMIT ) && ( "$dir" != "$last_dir" ) ]]; do
  last_dir="$dir"
  # Strip a level off.
  dir=${dir/#...\/*([^\/])/"..."} <- broken line
  echo $dir
done

echo $dir

如果我这样做

test=".../School/CS352/Project1"
text=${test/#...\/*([^\/])/"..."}

我得到.../CS352/Project1,这就是我想要的。但是同一个 sub 在我的脚本中什么也没做。

问题:如何使代码中的标记行表现得像上面的示例?

【问题讨论】:

  • gnu.org/software/bash/manual/html_node/Pattern-Matching.html 打开 shell 并测试示例。这显然无害,复制粘贴只需两行。
  • 此行为取决于是否设置了extglob shell 选项。默认情况下它是关闭的。大概您的脚本正在为交互式外壳打开它。
  • @Kevin -- 它不是正则表达式,但它是一种相当强大的语法(对于 BRE;当然不如 PCRE 那样富有表现力)。在手册页中搜索“extglob”。
  • 不要将答案编辑成问题。这样做意味着人们不能添加其他答案,也不能让他们在与接受的答案同等的基础上被赞成/反对;这也意味着问题本身不能独立于答案而被赞成/反对。

标签: bash string-substitution


【解决方案1】:

运行:

shopt -s extglob

...打开此支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多