簡體   English   中英

&&:的目的是什么? 在bash腳本中

[英]What is the purpose of && :; in bash scripts

我遇到了一個bash腳本,該腳本在一個函數中運行以下命令

set -e
rm -rf some_dir/* && :;

&& :;的目的是什么? 在這種情況下?

編輯:

我知道這是&& true的同義詞,但是現在我不明白為什么它繞過set -e

嘗試一下,我看到運行以下命令

#!/bin/bash -e

# false
echo false alone return 1 and fail with -e

false || true
echo "false || true return $?"

false || :;
echo "false || :; return $?"

false && true
echo "false && true return $?"

false && :;
echo "false && :; return $?"

false && :
echo "false && : return $?"

產出

false alone return 1 and fail with -e
false || true return 0
false || :; return 0
false && true return 1
false && :; return 1
false && : return 1

它抑制set -e效果的原因可以在手冊頁中找到:

-e      Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status.
        The shell does not exit if the command that fails is part of the  command  list  immediately
        following  a while or until keyword, part of the test in an if statement, part of a && or ||
        list, or if the command's return value is being inverted via !.  A trap on ERR, if  set,  is
        executed before the shell exits.

需要強調的是: The shell does not exit if the command that fails is ... part of a && or || list The shell does not exit if the command that fails is ... part of a && or || list

注意這里有些微妙之處。 一個常見的錯誤是編寫類似foo() { ...; rm path; #cleanup } foo() { ...; rm path; #cleanup } foo() { ...; rm path; #cleanup } ,目的是永遠成功。 我的意思是,代碼的編寫者甚至沒有真正考慮過foo的退出狀態,而是隱含地期望成功並且不關心rm的退出狀態,而忘記了foo返回rm的退出狀態。 可能會將代碼重寫為rm path || : rm path || :確保foo總是成功返回,或rm path && :返回rm的狀態,但如果啟用errexit則不退出。 坦白說,它太微妙了,我相信永遠不要使用set -e另一個原因。 此外,可能會提出一個論點,即除非您明確exit腳本或從函數return ,否則您永遠不應依賴代碼的退出狀態。

&&很容易解釋。 從bash man頁:

command1 && command2

僅當command1返回退出狀態為零時,才能執行command2。

:很難在文檔中找到。 :是一個等效於true的內置函數:

:; echo $? 
0

因此,總的來說,此命令等於:

遞歸刪除目錄,如果rm成功,則運行'true'。

但是,這似乎沒有必要,因為&&已經“測試”了rm是否返回true,所以有點像做true && true

更常見的是在需要if/else情況下使用else來做某事,例如,

if command1; then :; else command2; fi

盡管這僅在您的系統沒有true命令時才有用,但是對於以后的代碼閱讀者來說,這無疑會更容易。 (或者,您可以使用否定測試,而根本不用操心)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM