Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 947
Nuno Avatar asked Feb 06 '26 19:02

Nuno


2 Answers

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.log

Working 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
like image 115
markp-fuso Avatar answered Feb 09 '26 11:02

markp-fuso


One way...

#!/bin/bash
(
  blah code
) > file.log
like image 28
Bob Goddard Avatar answered Feb 09 '26 11:02

Bob Goddard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!