Search code examples
bashcomments

Handling logs of bash script and comments in text file


I am trying to read a text file which has few commented starts with '#', my bash script should read the lines of the text file which doesn't start with '#'. Also im trying to capture the output of echo statements in both logs and to show it console window for the user understanding.

I have tried to use the below query for capturing logs and printing in console

exec 2>&1 1>>$logfile

For reading each line of the file and calling the function, i have declared an array and to eliminate lines which starts with '#' , i have used the below query.

declare -a cmd_array 
while read -r -a cmd_array | grep -vE '^(\s*$|#)' 
do
  "${cmd_array[@]}" 
done < "$text_file"

Note : I need to eliminate the line starts with '#' and remaining lines to be read and place in array as declared.

Bash script 
***********

#! /bin/bash

Function_1()
{
now=$( date '+%Y%m%d%H%M' )
eval logfile="$1"_"$now".log
exec 2>&1 1>>$logfile     ### Capture echo output in log and printing in console 
#exec 3>&1 1>>$logfile 2>&1
echo " "
echo "############################"
echo "Function execution Begins"
echo "############################"
echo "Log file got created with file name as $1.log"
eval number=$1
eval  path=$2
echo "number= $number"
ls -lR $path >> temp.txt
        if [ $? -eq 0 ]; then
        echo " Above query executed."
        else
        echo "Query execution failed"
        fi
echo "############################"
echo "Function execution Ends"
echo "############################"
echo " "
}

text_file=$1
echo $text_file
declare -a cmd_array  ### declaring a array 
while read -r -a cmd_array | grep -vE '^(\s*$|#)'  ### Read each line in the file with doesnt starts with '#' & keep it in array
do
  "${cmd_array[@]}" 
done < "$text_file"


Text file 
*********
####################################    
#Test
#Line2
####################################
Function_1 '125' '' ''
Function_1 '123' '' ''

Solution

  • Consider piping the grep output into the read:

    declare -a cmd_array  ### declaring a array 
        ### Read each line in the file with doesnt starts with '#' & keep it in array
    grep -vE '^(\s*$|#)' < "$text_file" | while read -r -a cmd_array
    do
      "${cmd_array[@]}" 
    done
    

    I'm not clear about the output/logging comment. If you need the output appended to a file, in addition to stdout/console), consider using the 'tee' (probably 'tee -a')