在Linux中将输出从功能块重定向到文件

在Linux中将输出从功能块重定向到文件,linux,shell,unix,Linux,Shell,Unix,就像我们将for循环块的输出重定向到文件一样 for () do //do something //print logs done >> output file 类似地,在shell脚本中,有没有一种方法可以将输出从功能块重定向到文件,类似这样的 function initialize { //do something //print something } >> output file //call initialize

就像我们将for循环块的输出重定向到文件一样

for ()
do
  //do something
  //print logs
done >> output file
类似地,在shell脚本中,有没有一种方法可以将输出从功能块重定向到文件,类似这样的

function initialize {
         //do something
         //print something
} >> output file

//call initialize

如果没有,我还有其他方法可以做到这一点吗?请注意,我的函数有很多消息要打印在日志中。将输出重定向到每一行的文件将导致大量的I/O利用率。

您可以使用for
exec
进行shell重定向,但不确定它是否适用于函数

exec > output_file
function initialize {
  ...
}
initialize

在调用函数时执行重定向

#!/bin/bash
initialize() {
  echo 'initializing'
  ...
}
#call the function with the redirection you want
initialize >> your_file.log
或者,在函数中打开子shell并重定向子shell输出:

#!/bin/bash
initialize() {
  (  # opening the subshell
    echo 'initializing'
    ...
  # closing and redirecting the subshell
  ) >> your_file.log
}
# call the function normally
initialize

你的建议实际上是完全正确的。函数声明语法如下(强调)1所示:

函数是使用以下语法声明的:

name () compound-command [ redirections ] 或者,要附加到
输出文件

myappendfunc() {
    printf '%s\n' "$1"
} >> outfile
但是,即使您可以将目标文件的名称放入变量并重定向到该变量,如下所示:

fname=outfile

myfunc() { printf '%s\n' "$1"; } > "$fname"
我认为在调用函数的地方进行重定向更为清晰,就像其他答案中建议的那样。我只是想指出,可以将重定向作为函数声明的一部分



1这不是bashism:还允许在函数定义命令中重定向。

我的解决方案是包装函数

#!/bin/bash
initialize() {
  echo 'initializing'
  ...
}
#call the function with the redirection you want
initialize >> your_file.log
init_internal(){
echo“这是init_internal,参数:$@”
回显“arg1$1”
回显“arg2$2”
}
init(){
本地日志路径=$1
echo“日志地址:$LOG\u路径”
初始化内部“${@:2}”>./$LOG\U路径2>&1
}
init log.log a b c d
cat./log.log
它输出:

LOG at: log.log
this is init_internal with params: a b c d
arg1 a
arg2 b

我试着做同样的事情,并且我的函数编码和原来的问题完全一样
echo
语句存在于函数中,函数的右括号结束后,它重定向到stderr。这是可行的,但我这么做是为了验证这被认为是可行的。调用函数时执行重定向而不是让函数自己执行重定向的原因是什么?
LOG at: log.log
this is init_internal with params: a b c d
arg1 a
arg2 b