0
我正在寫一個腳本來使用bash參數替換去除工作目錄到有限的長度。它在命令行上工作,但同樣的替換在腳本中什麼也不做。爲什麼模式*([^ /])在我的交互式shell中工作,但不是腳本?
代碼:
#!/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在我的腳本中什麼也沒做。
問:如何使代碼中的標記行像上面的示例一樣?
https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html 打開一個shell並測試示例。這顯然不是有害的,而且它只是雙線複製。 – Tyler 2014-11-04 01:37:29
此行爲取決於是否設置了「extglob」shell選項。它默認關閉。據推測你的腳本正在開啓交互式shell。 – 2014-11-04 01:39:52
@Kevin - 這不是正則表達式,但它是一個相當強大的語法(對於BRE,當然不如PCRE表現力強)。在手冊頁中搜索「extglob」。 – 2014-11-04 01:40:09