如果我想在每次使用時git status將foo 的值設定為等于 bar ,我將如何繼續執行此操作?我的第一個想法是設定別名,status="status && foo=bar"但是當我嘗試這樣做并 echo $foo 我不會得到 bar 回顯但是如果我手動輸入所有內容git status && foo=baz,然后echo $foo我的輸出是 baz。為什么我不能在別名中宣告變數?我還觀察到,如果我要切換順序并且出于某種原因這樣做,alias git="foo=bar && git"并且如果我嘗試了任何 git 命令并回顯 foo 它等于 bar ...
uj5u.com熱心網友回復:
Git 別名通過以下方式運行:
- Git 本身,如果別名不以
!:開頭,在這種情況下你不能設定新的環境變數;或者 - 一個 POSIX 兼容的 shell,如果別名以
!.
POSIX 兼容的 shell 允許以兩種方式設定環境變數:
VAR=value command
或者:
VAR=value; export VAR; command1; command2; ...; commandN
第二個變體可以寫成:
export VAR=value; command1; ...; commandN
顯式匯出的變數是為所有以這種方式呼叫的命令設定的——而不是VAR=value command,它只為一個命令設定它——因為這個設定是在shell 中完成的,并且一直持續到 shell 本身退出,然后設定消失已經退出的shell。所以如果x是一個 Git 別名:
git x
運行該別名,它可以在別名本身運行的任何命令的持續時間內設定環境變數設定。然后運行這些命令的 shell 退出,所有設定都消失了。
因此,Git 別名實際上不可能在用于運行該別名的命令列 shell 中設定任何環境變數。這適用于所有命令,而不僅僅是 Git 命令:沒有命令可以在任何“外部”shell 中設定環境變數。
有一個逃生艙口,它是這樣的:當你自己撰寫一個 shell 命令時,你有控制權。例如,您可以撰寫相當愚蠢的 shell 命令:
export VAR=$(echo value)
其中括號$(echo value)被評估,然后它的輸出被替換。但這確實意味著如果某個程式列印了一些你想保存的值,你可以寫:
var=$(command)
它將本地 shell 變數var設定為輸出,或者:
export VAR=$(command)
它設定shell變數并將其匯出。(注意:這里的大寫只是約定俗成的:匯出的區域shell變數習慣上全大寫,而沒有匯出的區域shell變數習慣上全小寫。)
還有第二個逃生艙口,但使用它是有風險的:POSIX shell 有一個eval命令將文本反饋給 shell 解釋器。我們可以將其用于列印export VAR1=value1; export VAR2=value2為輸出的程式:
eval `ssh-agent -s`
Here, the ssh-agent program sets up the agent and then prints several appropriate export commands. However, should the ssh-agent program print rm -rf /, using eval ssh-agent -s will proceed to remove every file it can: this means you are placing a tremendous amount of trust on that ssh-agent command.
You can use a shell alias to make some easy-to-type-in command, such as gst, consist of both a variable-setting operation and a Git command:
alias gst='foo=bar && git status'
This is not a Git alias. This is a shell alias. POSIX now requires shell aliases (thanks to KamilCuk for the pointer). Bash always has them, though some very old non-bash shells might not have them.
uj5u.com熱心網友回復:
- 關于你的外殼的行為:
如果您撰寫以下腳本:
# test.sh:
#!/bin/bash
foo=bar
echo "from script: $foo"
然后運行它,您將看到以下內容:
$ ./test.sh && echo "from cli: $foo"
from script: bar
from cli:
運行該腳本會創建一個具有自己環境的全新行程,foo=bar在該環境中進行定義,并在行程退出后將其丟棄。
要在當前 shell 中定義 set 該變數,您必須使用其他方式。
@torek 提到:
eval ...使用腳本的輸出呼叫- 創建 shell 別名
我還要補充:
- 呼叫函式而不是腳本:
$ mytest () {
foo=bar
echo "from function: $foo"
}
$ mytest && echo "from cli: $foo"
from function: bar
from cli: bar
- 關于 git 別名:
git alias 將始終作為單獨的行程執行,如果您想設定一個“超過”呼叫的 env 變數,則必須使用其他一些構造。
例如,您可以在您的.bashrc:
mystatus () {
git status && foo=bar
}
之后,您將能夠mystatus從您啟動的任何 shell呼叫。
如果命令那么簡單,它真的相當于一個 bash 別名,好處是如果需要,可以更容易地擴展該函式的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338732.html
上一篇:使用bash中的find函式在子檔案夾上迭代運行程式
下一篇:使用awk計算示例檔案的字數
