How can I make a log file from my bash script?
I'm leaving the script without the options, all I want to know is how I can register the script being used and make a separate .log file.
Script:
#!/bin/bash
trash=~/TRASH
if [ ! -e $trash ]; then
mkdir $trash
elif [ ! -d $trash ]; then
echo "$0: error: $trash is not a directory"; exit 1
fi
while getopts "hr:t:s:u:" options; do
case $options in
#ALL THE OPTIONS AREN'T HERE FOR THE PURPOSE OF KEEPING IT SHORTER
shift $((OPTIND-1))
while [ $# -gt 0 ]; do
if [ ! -e $1 ]; then
echo "$0: error: tried to delete file that does not exist: $1"
shift
continue
fi
tarname="$1.tar"
tar -cf "$tarname" "$1"
mv "$tarname" $trash
rm -rf "$1"
shift
done
To display stdout and stderr to both the console and the log, and to append to the log, perhaps something like:
#!/bin/bash
{
blah code
} 2>&1 | tee -a file.log
Where:
2>&1 - redirect stderr to stdout| tee -a file.log - send stdout to console but also 'tee' up a copy to be -appended to file.logWorking example:
$ cat blah
#!/bin/bash
{
echo "hello" # will print to stdout
dirxys # will send message to stderr
} 2>&1 | tee -a blah.log
###########
# both stdout/stderr show up on console:
$ ./blah
hello
./blah: line 5: dirxys: command not found
###########
# both stdout/stderr also show up in log:
$ cat blah.log
hello
./blah: line 5: dirxys: command not found
One way...
#!/bin/bash
(
blah code
) > file.log
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With