如何使用空格 hack 使別名尾隨與提供的參數一起工作

如何使用空格 hack 使別名尾隨與提供的參數一起工作

我有兩個別名watchExpandl。我知道您可以透過放置尾隨空格來使 bash 擴展與別名一起使用,如下所示:

alias watchExpand='watch '

l別名為ls -larthiF --context.所以當我輸入命令時,watchExpand l它就像一個魅力。

但是,如果我向命令提供參數watchExpand,例如

watchExpand -n 1 l

我的l別名不再有效。如何在參數後獲得 bash 擴充?

答案1

這是我的壞主意思考你要求:

function watchExpand() {
  e=""
  for param in $@
  do
    if alias $param >/dev/null 2>&1
    then
      exp=$(alias $param | cut -d= -f2| sed -e s/^\'// -e s/\'\$//)
      e+=" $exp"
    else
      e+=" $param"
    fi
  done
  watch $e
}

答案2

Zsh 有全域別名。你可以這樣做:

alias -g @l='ls -larthiF --context'

進而:

watch -n 1 @l

請注意,這@不是強制性的,但我用它來避免無意中呼叫全域別名。

答案3

我用我的方式找出解決方案。

首先,我建立一個名為「addExpand」的函數,以便根據需要更輕鬆地新增別名/函數。

xb@dnxb:/tmp/t$ type -a addExpand
addExpand is a function
addExpand () 
{ 
    echo -e "#!/bin/bash\nshopt -s expand_aliases\n. ~/.bash_aliases 2>/dev/null\n$1"' "$@"' | sudo tee /usr/bin/e_"$1";
    sudo chmod +x /usr/bin/e_"$1"
}
xb@dnxb:/tmp/t$ addExpand l
#!/bin/bash
shopt -s expand_aliases
. ~/.bash_aliases 2>/dev/null
l "$@"

運行後addExpand l,別名l將建立為名為的可執行文件/usr/bin/e_l包含以下內容:

xb@dnxb:/tmp/t$ cat /usr/bin/e_l
#!/bin/bash
shopt -s expand_aliases
. ~/.bash_aliases 2>/dev/null
l "$@"

現在享受使用別名/函數的擴展版本:

xb@dnxb:/tmp/t$ watch --color -n 1 e_l /tmp //works like a charm !!!
xb@dnxb:/tmp/t$ 

筆記:

[1] e_l,前綴為 'e_' 表示它是指令的擴充版本。

[2] 如果使用 運行,我感覺太重了,無法每秒執行一次採購watch -n 1。我可能需要找到一種方法來解決這個問題。

[3] 另一個缺點是它不能遞歸地解析別名。

相關內容