This is a very common scenario to log the application messages into a separate file; Here, we will see a Shell script how to write logs in a separate file.

Shell Script How to write logs in a separate file:

To make this use-case simple and more reusable, I am writing two different script files one is to write the messages to the log file, and another one is for generating the logs.

Create file which will be responsible for logging the different types of log messages like INFO, WARN and ERROR into application.log file.



     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- WARN -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};

     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- INFO -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};

     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- ERROR -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
     exit 1;

Create a simple shell script to write some messages into application.log file.


#Getting current directory
readonly CURRENT_DIR=$(cd `dirname $0`; pwd -P)
source ${CURRENT_DIR}/

logInfo "I am information"
logWarn " I am a Warning message"
logError "I am an Error"

Make both files as executable.

$chmod 777
$chmod 777

Run file and see the application.log file.


check the application.log file

$ more application.log
--[2020/04/16 15:41:07] -- INFO -- I am information
--[2020/04/16 15:41:07] -- WARN --  I am a Warning message
--[2020/04/16 15:41:07] -- ERROR -- I am an Error

Happy Learning 🙂