bashshellio-redirectiontee

How to create log file from my bash script


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

Solution

  • 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:



    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