wasp256
wasp256

Reputation: 6242

Redirect echo output in shell script to logfile

I have a shell script with lots of echo in it. I would like to redirect the output to a logfile. I know there is the command call cmd > logfile.txt, or to do it in the file echo 'xy' > logfile.txt, but is it possible to simply set the filename in the script which then automatically writes all echo's to this file?

Upvotes: 42

Views: 202572

Answers (6)

Sandeep Singh
Sandeep Singh

Reputation: 7990

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will throw a syntax error.

Upvotes: 27

Ahsan Horani
Ahsan Horani

Reputation: 319

To get output on console and log output in a file:

script.sh

#!/bin/bash
(
  #Command 1
  #Command 2
  #Command 3
  ...
) 2>&1 | tee /path/to/save/console_output.log

Upvotes: 3

anubhava
anubhava

Reputation: 784898

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec >logfile.txt 2>&1

OR else to redirect only stdout use:

exec > logfile.txt

Upvotes: 62

#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"

Output:

> ./above_script.sh                                                                
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file

Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html

Upvotes: 4

Elayaraja Dev
Elayaraja Dev

Reputation: 208

LOG_LOCATION="/path/to/logs"    
exec >> $LOG_LOCATION/mylogfile.log 2>&1

Upvotes: 5

txipi
txipi

Reputation: 141

You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

Upvotes: 14

Related Questions