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 (220.127.116.11) 56(84) bytes of data.
64 bytes from 18.104.22.168: icmp_seq=1 ttl=60 time=28.8 ms
64 bytes from 22.214.171.124: icmp_seq=2 ttl=60 time=77.0 ms
64 bytes from 126.96.36.199: icmp_seq=3 ttl=60 time=48.3 ms
64 bytes from 188.8.131.52: 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)
date; # This will print the date
./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
exec > log.txt
echo "Just test"
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)
[COMMAND]| tee [OUTPUT_FILE]
date |& tee log.txt
Print a script output to a file and print to the terminal, from terminal
test.sh 2>&1 | tee log.txt
bash test.sh 2>&1 | tee log.txt
Print a script output to a file and print to the terminal, from the script.
# Test script
exec > >(tee -ia log.txt)
# exec 2> >(tee -ia log.txt >&2)
# commands to run.
ping -c 4 drupal.org;