Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting output from a function block to a file in Linux

Tags:

linux

shell

unix

Just like we redirect output from a for loop block to a file

for ()
do
  //do something
  //print logs
done >> output file

Similarly in shell script, is there a way to redirect output from a function block to a file, something like this?

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

//call initialize

If not, is there some other way I can achieve that? Please note my function has lot of messages to be printed in a log. Redirecting output to a file at every line would result in a lot of I/O utilization.

like image 953
dig_123 Avatar asked Aug 07 '13 05:08

dig_123


People also ask

How do I redirect output to a file in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.

How do I redirect console output to a file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

Which redirection operator redirects output to a file?

The > symbol is known as the output redirection operator. The output of a process can be redirected to a file by typing the command followed by the output redirection operator and file name.

How do I redirect a output to a file in bash?

To use bash redirection, you run a command, specify the > or >> operator, and then provide the path of a file you want the output redirected to. > redirects the output of a command to a file, replacing the existing contents of the file.


1 Answers

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
like image 139
Carlos Campderrós Avatar answered Sep 28 '22 05:09

Carlos Campderrós