2013-02-21 28 views
1

我試圖構建一個快速腳本來查找目錄下的所有git repos,並依次「git pull」每一個。使用xargs將命令傳遞給子shell在別名內不起作用

這是我迄今發現:

find ~/ -name ".git" -type d | sed 's,/*[^/]\+/*$,,' | xargs -L1 bash -c 'cd "$1" && git pull' _ 

如果粘貼到終端,這將工作完全因爲它的預期。但是,如果我讓這成爲一個別名我.bashrc文件:

alias gpa="find ~/ -name ".git" -type d | sed 's,/*[^/]\+/*$,,' | xargs -L1 bash -c 'cd "$1" && git pull' _" 

的命令不起作用。我修改了它,企圖得到它打印的內容通過xargs的啓動子shell正在接收:

alias printgpa="find ~/ -name ".git" -type d | sed 's,/*[^/]\+/*$,,' | xargs -L1 bash -c 'echo "$1"' _" 

運行時,每個子shell打印一個換行符,但沒有別的。

任何人都可以回答爲什麼會發生這種情況嗎?我的直覺告訴我這是別名中的語法問題,但我不知道到底發生了什麼。

+0

'在bash會得到它呼應的命令設置-x'它認爲他們,就在執行它們之前。非常適合整理棘手的報價問題。 – bobbogo 2013-02-21 18:26:31

+0

你可能想使用一個函數而不是別名,這樣你就不用擔心棘手的引用來使它工作。 – chepner 2013-02-21 20:01:14

回答

2

問題是$1在定義別名時被替換,而不是在運行它時。爲了避免這種情況,您需要引用$,可以使用反斜槓或使用一些單引號。例如:

alias printgpa='find ~/ -name .git -type d | sed '\''s,/*[^/]\+/*$,,'\'' | xargs -L1 bash -c '\''echo "$1"'\'' _' 
+1

優秀!非常感謝,這完美的作品。我的別名現在說: 'alias gpa =「find〜/ -name」.git「-type d | sed's,/ * [^ /] \ +/* $ ,,'| xargs -L1 bash - c'cd「\ $ 1」&& git pull'_「' – lelandbatey 2013-02-21 18:32:22

+0

@lelandbatey:不客氣! – ruakh 2013-02-21 18:36:53

+0

@MartijnPieters:很好的答案。 OP沒有接受它,但是從我+1。 – user1284631 2013-08-07 07:50:28

2

也許是容易當你使用GNU並行閱讀:

alias gpa="find ~/ -name .git -type d | parallel 'cd {//} && git pull'" 

另外,你得到更多的控釋片平行拉的好處。

它需要從字面上10秒安裝GNU並行:

wget pi.dk/3 -qO - | sh -x 

觀看介紹視頻,以瞭解更多:https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

+1

+1 for Parallel,但是寫一個腳本來安裝一個經常可用的工具,你的操作系統的軟件存儲庫會有點麻煩。我不確定鼓勵人們如何執行腳本是一個好主意。 – JeroenHoek 2014-06-13 19:04:55

相關問題