將所有程式碼行重定向到同一文件中的一行

將所有程式碼行重定向到同一文件中的一行

我有以下命令集用於更新我的託管提供者平台上的 CentOs 共享託管分區中的所有 WordPress 網站(透過每日 cron)。

wp該組內的命令pushd-popdWP-CLI程序,它是一個 Bash 擴展,用於 WordPress 網站上的各種 shell 級操作。

for dir in public_html/*/; do
    if pushd "$dir"; then
        wp plugin update --all
        wp core update
        wp language core update
        wp theme update --all
        popd
    fi
done

目錄public_html是所有網站目錄所在的目錄(每個網站通常有一個資料庫和一個主檔案目錄)。

鑑於public_html有一些目錄哪些不是WordPress 網站目錄,然後 WP-CLI 將傳回有關它們的錯誤。

為了防止這些錯誤,我想我可以這樣做:

for dir in public_html/*/; do
    if pushd "$dir"; then
        wp plugin update --all 2>myErrors.txt
        wp core update 2>myErrors.txt
        wp language core update 2>myErrors.txt
        wp theme update --all 2>myErrors.txt
        popd
    fi
done

2>myErrors.txt有沒有一種方法可以確保每個命令中的所有錯誤都會在一行中寫入同一個文件,而不是寫入四次(或更多)?

答案1

運算子> file打開file進行寫入,但最初將其截斷。這意味著每個新文件> file都會導致文件內容被取代。

如果您希望myErrors.txt包含所有命令的錯誤,則需要僅開啟該檔案一次,或使用>第一次和>>其他時間(這將在附加模式)。

在這裡,如果您不介意pushd/popd錯誤也轉到日誌文件,您可以重定向整個for循環:

for dir in public_html/*/; do
    if pushd "$dir"; then
            wp plugin update --all
            wp core update
            wp language core update
            wp theme update --all
        popd
    fi
done  2>myErrors.txt

或者,您可以在高於 2、3 的 fd 上開啟日誌文件,然後對要重定向到日誌文件的每個命令或命令組使用2>&3(或2>&3 3>&-以免用不需要的 fd 污染命令) :

for dir in public_html/*/; do
    if pushd "$dir"; then
          {
            wp plugin update --all
            wp core update
            wp language core update
            wp theme update --all
          } 2>&3 3>&-
        popd
    fi
done  3>myErrors.txt

答案2

您可以使用花括號團體一個區塊並重定向所有輸出:

for dir in public_html/*/; do
    if pushd "$dir"; then
        {
            wp plugin update --all
            wp core update
            wp language core update
            wp theme update --all
        } 2>myErrors.txt
        popd
    fi
done

相關內容