就像我们将for循环块的输出重定向到文件
一样for ()
do
//do something
//print logs
done >> output file
同样在shell脚本中,有没有办法将输出从功能块重定向到文件,就像这样?
function initialize {
//do something
//print something
} >> output file
//call initialize
如果没有,还有其他方法可以实现吗?请注意我的功能有很多消息要打印在日志中。将输出重定向到每行的文件将导致大量的I / O利用率。
答案 0 :(得分:9)
调用函数时进行重定向。
#!/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 :(得分:9)
你建议的方式实际上是完全有效的。 Bash manual给出了函数声明语法如下(强调我的) 1 :
使用以下语法声明函数:
name () compound-command [ redirections ]或
function name [()] compound-command [ redirections ]
所以这将是完全有效的,并用outfile
的参数替换myfunc
的内容:
myfunc() {
printf '%s\n' "$1"
} > outfile
或者,要附加到outfile
:
myappendfunc() {
printf '%s\n' "$1"
} >> outfile
但是,即使您可以将目标文件的名称放入变量并重定向到该变量,如下所示:
fname=outfile
myfunc() { printf '%s\n' "$1"; } > "$fname"
我认为在你调用函数时进行重定向会更清楚 - 就像在其他答案中推荐的那样。我只是想指出你可以将重定向作为函数声明的一部分。
1 这不是一个基础:POSIX Shell spec也允许在函数定义命令中重定向。
答案 2 :(得分:3)
您可以使用exec
进行shell重定向,不确定它是否适用于函数
exec > output_file
function initialize {
...
}
initialize
答案 3 :(得分:0)
我的解决方案是包装函数。
init_internal(){
echo "this is init_internal with params: $@"
echo "arg1 $1"
echo "arg2 $2"
}
init() {
local LOG_PATH=$1
echo "LOG at: $LOG_PATH"
init_internal "${@:2}" > ./$LOG_PATH 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