Reputation: 89
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
Upvotes: 2
Views: 23592
Reputation: 946
late answer
this with parenthesis dont work for sh files of type wget that ... wget that ... wget that ...
Solution:
./script.sh 2>&1 | tee -a file.log
Upvotes: 0
Reputation: 33914
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 -a
ppended to file.log
Working example:
$ cat blah
(
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 3: dirxys: command not found
# both stdout/stderr also show up in log:
$ cat blah.log
hello
./blah: line 3: dirxys: command not found
Upvotes: 7
Reputation: 1838
Just call the script and redirect its output:
./script.sh > script.log
Upvotes: 1