[英]Loop over bash aliases and run commands in script
我正在嘗試創建一個具有別名列表的 bash 腳本並在我的腳本中運行它們。 (這只是一個簡化的例子,但它解釋了這種情況)。
應該發生的是我遍歷我的別名並且腳本一一執行它們。
別名列表.sh
#!/bin/bash
alias al1="ls"
alias al2="ls ."
alias al3="ls .."
test_alias_loop.sh
#!/bin/bash -i
# Expand aliases
shopt -s expand_aliases
source ~/Documents/test_ssh_bash/scripts/alias_list.sh
# Exists just to get a list of aliases, proper version gets aliases from bash command
aliases=$(printf "al1\nal2\nal3\n\n")
for ssh_alias in $aliases; do
echo "$ssh_alias"
$ssh_alias
done
這是我得到的第一個命令。/test_alias_loop.sh: line 12: al1: command not found
但是,當我這樣做的時候
al1
命令運行,我得到了當前目錄的 ls 。
如何遍歷別名命令列表並在我的腳本中實際運行它們?
如果目的是檢查以確保別名有效,則在處理后將它們傳送到 bash 似乎有效。
$alias ls1='ls 1'
$alias ls2='ls 2'
$alias ls3='ls 3'
$alias |
while read -r line ; do
echo "$line" |
perl -pe 's/.*?=//' |
xargs
done | bash
給出:
ls: cannot access '1': No such file or directory
ls: cannot access '2': No such file or directory
ls: cannot access '3': No such file or directory
您的問題可以簡化為以下示例:
alias xx=echo
foo=xx;
$foo text.
你會得到bash: xx: command not found 。 似乎命令在變量擴展之后不再被視為可能的別名。 這可以從bash手冊頁中的以下句子中解釋:
Aliases allow a string to be substituted for a word when it is used as the
first word of a simple command.... The first word of each simple command, if
unquoted, is checked to see if it has an alias.
雖然它沒有明確說明,但我認為命令中的第一個單詞在任何其他替換之前都經過測試。
但是,即使您找到解決此問題的方法,您的腳本也無法正常工作,因為 - 正如手冊頁所說 - :
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt.
因此,要在腳本中使用別名,您必須明確打開此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.