Search code examples
bashshelldatelogfilelogfile-analysis

shell script not running but command line running


I have a Error Log file with contents as -

2017/11/06 13:17:05 [notice] 18164#18164: signal process started
.
.
.

I have command that will extract the date and notice,warn message

cat  whole_error.log | cut -d" " -f1,3,5-20 | sort -nr | grep "warn\|notice" | awk '$1 >= 2017/09/02 && $1 <= 2017/11/06' | awk '{print $1 " " $2" " $3}'

Its working fine entirely, i am getting the expected output But, i want to take the start date and end date as command line argument input and for that, i wrote the script as -

#!/bin/bash
file_name=$1
start_date=$2
end_date=$3


cat  $file_name | cut -d" " -f1,3,5-20 | sort -nr | grep "warn\|notice" | awk '$1 >= $start_date && $1 <= $end_date' | awk '{print $1 " " $2" " $3}'

But its not returning anything. No error message nothing..Just the prompt arrives again. How to fix this..


Solution

  • Use -v to pass shell variables into awk:

    #!/bin/bash
    
    file_name=$1
    start_date=$2
    end_date=$3
    
    <"$file_name" cut -d" " -f1,3,5-20 \
      | sort -nr \
      | awk -v start_date="$start_date" -v end_date="$end_date" \
          '/warn|notice/ && $1 >= start_date && $1 <= end_date {print $1 " " $2" " $3}'