我正在运行以下git clone
命令sudo
,bash
并且想将STDOUT重定向到日志文件:
% sudo -u test_user bash -c "git clone https://github.com/scrooloose/nerdtree.git
/home/test_user/.vim/bundle/nerdtree >> /var/log/build_scripts.log"
发生了什么事,STDOUT正在继续发送到终端。IE
Cloning into 'nerdtree'...
remote: Counting objects: 3689, done.
[...]
Checking connectivity... done.
我猜这个问题与以下事实有关sudo
:先创建一个新进程,然后再bash
创建另一个进程,如下所示:
% sudo -u test_user bash -c "{ git clone https://github.com/scrooloose/nerdtree.git
/home/test_user/.vim/bundle/nerdtree >> /var/log/build_scripts.log; ps f -g$$; }"
PID TTY STAT TIME COMMAND
6556 pts/25 Ss 0:02 /usr/bin/zsh
3005 pts/25 S+ 0:00 \_ sudo -u test_user bash -c { git clone https://github.com/scrooloo
3006 pts/25 S+ 0:00 \_ bash -c { git clone https://github.com/scrooloose/nerdtree.
3009 pts/25 R+ 0:00 \_ ps f -g6556
我试过了
exec >> /var/log/build_script.log
命令并在命令之前使用但是我认为这些重定向仅适用于父级,子进程默认将STDOUT发送到其父级的进程,/dev/tty/25
从而导致输出继续发送到终端。
如何重定向此命令的STDOUT?
您提到的消息不会打印到标准输出,而是打印到标准错误。因此,要捕获它们,您需要重定向标准错误而不是标准输出:
sudo -u user bash -c "git clone https://github.com/foo.git ~/foo 2>> log"
或STDERR和STDOUT:
sudo -u user bash -c "git clone https://github.com/foo.git ~/foo >> log 2>&1"
使用bash
,您还可以使用&>>
:
sudo -u user bash -c "git clone https://github.com/foo.git ~/foo &>> log"
的csh
,tcsh
,zsh
相当于存在>>&
((t)csh
不支持2>&1
所以它的唯一办法):
sudo -u user csh -c "git clone https://github.com/foo.git ~/foo >>& log"
在 fish
sudo -u user fish -c "git clone https://github.com/foo.git ~/foo >> log ^&1"
有关各种不同类型的重定向运算符的更多信息,请参见Shell的控制和重定向运算符是什么?
现在,在的特定情况下git
,还有另一个问题。像其他一些程序一样,git
可以检测到其输出正在重定向,并且可以停止打印进度报告。这可能是因为报告旨在实时显示并包含\r
在保存在文件中时可能出现的问题。要解决此问题,请使用:
--progress
Progress status is reported on the standard error stream by default
when it is attached to a terminal, unless -q is specified. This
flag forces progress status even if the standard error stream is
not directed to a terminal.
和:
sudo -u user bash -c "git clone --progress https://github.com/foo.git ~/foo >> log 2>&1"
如果您想同时看到输出并保存到文件,请使用tee
:
sudo -u user bash -c "git clone --progress https://github.com/foo.git ~/foo 2>&1 |
tee -a log
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句