在一行中将所有代码行重定向到同一个文件

use*_*970 1 cron centos error-handling hosting-services wordpress

我有以下命令集用于更新我的托管服务提供商平台上 CentOs 共享托管分区中的所有 WordPress 站点(通过每日 cron)。

集合中的wp命令pushd-popd属于WP-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
Run Code Online (Sandbox Code Playgroud)

目录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
Run Code Online (Sandbox Code Playgroud)

而不是写2>myErrors.txt四次(或更多),有没有办法确保来自每个命令的所有错误都将进入同一文件,在一行中?

Sté*_*las 5

> 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
Run Code Online (Sandbox Code Playgroud)

或者,例如,您可以在 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
Run Code Online (Sandbox Code Playgroud)