How do I save command output with logsave
- 2020-09-16 07:54:45
- OfStack
preface
What would you do if you wanted to save the output of a command to a file?
One common method is to use IO redirects
ls >/tmp/ls.txt 2>&1
We can use the tee command if we need to save the output of the command to a file and also output the content to the screen
ls |tee /tmp/ls.txt
Today, however, I found an logsave command that also saves command output to a file and outputs content pages to the screen.
The grammar of logsave is very simple:
logsave [ -asv ] logfile cmd_prog [args ... ]
options
-ES23en: Appends information to the specified log file.
parameter
logsave will execute cmd_prog args... And saves a copy of the command output to logfile, which is great because even if the directory logfile is in doesn't exist, logsave will save the output to memory and write it to the log file after the directory logfile is in is established
This feature of logsave makes it ideal for system startup scripts, where output is stored in memory until the /var/ directory is mounted before being written to /var/log/
Take the following example
# Delete store logfile The directory where the
rm -rf /tmp/logdir
# use logsave save logfile
logsave /tmp/logdir/logfile bash -c "sleep 2;date"
# create logdir
mkdir /tmp/logdir
echo To view logfile Whether to generate :
ls -l /tmp/logdir
echo Waiting for the 2s after :
sleep 2
echo Look again at logfile Whether to generate :
ls -l /tmp/logdir
echo To view logfile The content of the :
cat /tmp/logdir/logfile
2018 years 05 month 14 day week 1 16:31:44 CST
To view logfile Whether to generate :
The total amount 0
Waiting for the 2s after :
Look again at logfile Whether to generate :
The total amount 4
-rw-r--r-- 1 lujun9972 lujun9972 141 5 month 14 16:31 logfile
To view logfile The content of the :
Log of bash -c sleep 2;date
Mon May 14 16:31:42 2018
2018 years 05 month 14 day week 1 16:31:44 CST
Mon May 14 16:31:44 2018
----------------
It can be seen that:
Although logfile could not be generated at the beginning of 1 due to the non-existence of logdir, logsave finally managed to generate logfile after creating logdir and wrote the execution result of date command into it. logsave not only writes the output of the command to logfile, but also includes the command executed, the start time of command execution, and the end time of command execution.cmd_prog in logsave can be a special -, which means that logsave gets the content to be logged from standard input, making logsave available for use like tee 1
ls |wc -l |logsave /tmp/1.txt - >/dev/null
cat /tmp/1.txt
conclusion