Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress error from a single line of script

Tags:

bash

I'm reading in a log file checking for the log chronological sequence. I'm reading the log file into an array, only storing correctly formatted timestamp log lines:

MESSAGE_ONE is the line read from the file.

Timestamp1=$(echo "$MESSAGE_ONE" | cut -c1-20)
Timestamp1date=$(date -d "$Timestamp1" +%s) This line produces an error for incorrectly formatted lines

I handle the error as follows:

if [ "$?" = "1" ]; then
continue
else
Add the valid log line into the array

It works the way I want it to; all I want to do is suppress the error produced by badly formatted log entries. I've tried

Timestamp1date=$(date -d "$Timestamp1" +%s) 2>/dev/null

but it didn't work. I don't want to suppress all errors output by using 2>/dev/null after the cli command. Can someone help please?

like image 731
Andy Kendall Avatar asked Nov 25 '25 03:11

Andy Kendall


1 Answers

Redirection should be inside the sub shell, so use:

Timestamp1date=$(date -d "$Timestamp1" '+%s' 2>/dev/null)
like image 98
anubhava Avatar answered Nov 28 '25 01:11

anubhava



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!