Redirecting output from a function block to a file in Linux
The way you suggest is actually perfectly valid. The Bash manual gives the function declaration syntax as follows (emphasis mine)1:
Functions are declared using this syntax:
name () compound-command [ redirections ]or
function name [()] compound-command [ redirections ]
So this would be perfectly valid and replace the contents of outfile
with the argument to myfunc
:
myfunc() {
printf '%s\n' "$1"
} > outfile
Or, to append to outfile
:
myappendfunc() {
printf '%s\n' "$1"
} >> outfile
However, even though you can put the name of your target file into a variable and redirect to that, like this:
fname=outfile
myfunc() { printf '%s\n' "$1"; } > "$fname"
I think think it's much clearer to do the redirection where you call the function – just like recommended in other answers. I just wanted to point out that you can have the redirection as part of the function declaration.
1And this is not a bashism: the POSIX Shell spec also allows redirections in the function definition command.
Do the redirection when you are calling the function.
#!/bin/bash
initialize() {
echo 'initializing'
...
}
#call the function with the redirection you want
initialize >> your_file.log
Alternatively, open a subshell in the function and redirect the subshell output:
#!/bin/bash
initialize() {
( # opening the subshell
echo 'initializing'
...
# closing and redirecting the subshell
) >> your_file.log
}
# call the function normally
initialize
You can use for exec
for shell redirection not sure if it will work for functions
exec > output_file
function initialize {
...
}
initialize