【问题标题】:How do I redirect stdout to a variable and stderr to a file in ubuntu?如何将 stdout 重定向到变量并将 stderr 重定向到 ubuntu 中的文件?
【发布时间】:2015-08-08 21:55:26
【问题描述】:

我有这个命令,它会输出一个警告和我的结果。我想要一个变量中的结果,以便稍后在 shell 脚本中使用它并将错误重定向到日志文件。

这是我到目前为止所得到的。

wp post create --post_type=post --post_title='A future post' --post_status=publish --post_date='2015-01-01 07:00:00' --user=wordpress --url=vip.local/fusion --post_name='mock-post' --porcelain --quiet 2>&1 1>stdout.log | tee stderr.log

但我希望标准输出位于变量中,并将任何错误留给stderr.log

这是命令的输出

PHP Notice:  The called constructor method for WP_Widget is <strong>deprecated</strong> since version 4.3.0! Use <pre>__construct()</pre> instead. in /srv/www/wp/wp-includes/functions.php on line 3457
PHP Stack trace:
PHP   1. {main}() /usr/local/src/wp-cli/bin/wp:0
PHP   2. include() /usr/local/src/wp-cli/bin/wp:4
PHP   3. include() phar:///usr/local/src/wp-cli/bin/wp/php/boot-phar.php:5
PHP   4. require() phar:///usr/local/src/wp-cli/bin/wp/php/wp-cli.php:26
PHP   5. do_action() phar:///usr/local/src/wp-cli/bin/wp/php/wp-settings-cli.php:349
PHP   6. call_user_func_array() /srv/www/wp/wp-includes/plugin.php:503
PHP   7. wp_widgets_init() /srv/www/wp/wp-includes/plugin.php:503
PHP   8. do_action() /srv/www/wp/wp-includes/default-widgets.php:1650
PHP   9. call_user_func_array() /srv/www/wp/wp-includes/plugin.php:503
PHP  10. __lambda_func() /srv/www/wp/wp-includes/plugin.php:503
PHP  11. register_widget() /srv/www/wp-content/plugins/polldaddy/polldaddy-org.php(1075) : runtime-created function:1
PHP  12. WP_Widget_Factory->register() /srv/www/wp/wp-includes/widgets.php:720
PHP  13. PD_Top_Rated->PD_Top_Rated() /srv/www/wp/wp-includes/widgets.php:591
PHP  14. WP_Widget->WP_Widget() /srv/www/wp-content/plugins/polldaddy/polldaddy-org.php:950
PHP  15. _deprecated_constructor() /srv/www/wp/wp-includes/widgets.php:176
PHP  16. trigger_error() /srv/www/wp/wp-includes/functions.php:3457
132048 # << This is the stdout

数字132048 是我想要的变量输出,PHP Notice 是stderr。我本可以再次将 stdout 读取到变量中,但我认为一定有更好的方法。

【问题讨论】:

    标签: shell ubuntu command-line


    【解决方案1】:

    您可以使用反引号将命令的输出存储在变量中,并使用 2&gt; 将 stderr 重定向到文件:

    VARIABLE=`command --opt arg 2> stderr.log`
    

    在你的情况下,这样的事情应该可以工作:

    VARIABLE=`wp post create --post_type=post --post_title='A future post' --post_status=publish --post_date='2015-01-01 07:00:00' --user=wordpress --url=vip.local/fusion --post_name='mock-post' --porcelain --quiet 2> stderr.log`
    

    【讨论】:

      猜你喜欢
      • 2014-07-22
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 2012-06-16
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多