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

dig*_*123 13 unix linux shell

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

for ()
do
  //do something
  //print logs
done >> output file
Run Code Online (Sandbox Code Playgroud)

同样在shell脚本中,有没有办法将输出从功能块重定向到文件,这样的话?

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

//call initialize
Run Code Online (Sandbox Code Playgroud)

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

Car*_*rós 11

在调用函数时进行重定向.

#!/bin/bash
initialize() {
  echo 'initializing'
  ...
}
#call the function with the redirection you want
initialize >> your_file.log
Run Code Online (Sandbox Code Playgroud)

或者,在函数中打开子shell并重定向子shell输出:

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


Ben*_* W. 11

你建议的方式实际上是完全有效的.的击手册给出了函数声明的语法如下(重点煤矿)1:

使用以下语法声明函数:

name () compound-command [ redirections ]

要么

function name [()] compound-command [ redirections ]

所以这将是完全有效的outfile,并将参数的内容替换为myfunc:

myfunc() {
    printf '%s\n' "$1"
} > outfile
Run Code Online (Sandbox Code Playgroud)

或者,附加到outfile:

myappendfunc() {
    printf '%s\n' "$1"
} >> outfile
Run Code Online (Sandbox Code Playgroud)

但是,即使您可以将目标文件的名称放入变量并重定向到该变量,如下所示:

fname=outfile

myfunc() { printf '%s\n' "$1"; } > "$fname"
Run Code Online (Sandbox Code Playgroud)

我认为在你调用函数时进行重定向会更清楚 - 就像在其他答案中推荐的那样.我只是想指出你可以将重定向作为函数声明的一部分.


1这不是一个基础:POSIX Shell规范还允许在函数定义命令中重定向.