How to manage linux shell stdout ?
How to save linux shell output to a file ?
How to ptint linux shell output (stdout) to the terminal and save to a file ?
How redirect a copy of stdout to log file from within bash script itself ?
The linux shell/bash terminal default behaviour is print output to the terminal (StdOut : Standard output). But sometimes we need to change this behaviour like save toi a file, display noting ... Here some exaple of user case.
Print output to a file (log.txt)
Example : Save ping outout to a file.
ping -c 4 drupal.org > log.txt
So this command will create a file log.txt contains:
PING drupal.org (151.101.1.175) 56(84) bytes of data.
64 bytes from 151.101.1.175: icmp_seq=1 ttl=60 time=28.8 ms
64 bytes from 151.101.1.175: icmp_seq=2 ttl=60 time=77.0 ms
64 bytes from 151.101.1.175: icmp_seq=3 ttl=60 time=48.3 ms
64 bytes from 151.101.1.175: icmp_seq=4 ttl=60 time=16.5 ms
--- drupal.org ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
rtt min/avg/max/mdev = 16.521/42.689/77.006/22.838 ms
Print shell script output to a file (From terminal)
Script (test.sh):
#!/bin/bash
date; # This will print the date
Command
./test.sh > log.txt
This will display nothis on terminal, but print the date in to the file log.txt, like:
Fri Jun 16 11:14:27 CEST 2017
Redirect all outputs to a file
To print all outputs of the terminal in to a file, just type exec > THE_FILE_NAME
Example:
exec > log.txt
echo "Just test"
date
... ...
Not print the result, just execute the command
Example: run script but print to nothing.
# Out to nothing
./test.sh > /dev/null
Print a command output to a file and print to the terminal (stdout)
Example:
[COMMAND]| tee [OUTPUT_FILE]
date |& tee log.txt
Print a script output to a file and print to the terminal, from terminal
Examples:
test.sh 2>&1 | tee log.txt
# Or
bash test.sh 2>&1 | tee log.txt
Print a script output to a file and print to the terminal, from the script.
Script :
#!/bin/bash
#
# Test script
exec > >(tee -ia log.txt)
# OR
# exec 2> >(tee -ia log.txt >&2)
#
# commands to run.
date;
ping -c 4 drupal.org;
Command :
./test.sh
Comments