Tag: Bash

Linux – How to cut a log file based on timestamp

You can use the command ‘sed’ to specify an interval to cut a log file. ‘sed’ performs editing operations on information coming from standard input or a file. It edits line-by-line and in a non-interactive way.

Example to cut a log file based on timestamp:

sed '1,/2017\/01\/11 09\:00/ d;/2017\/01\/11 10\:00/,$ d' <logfile>

This command will just show lines between ‘2017/01/11 09:00’ and ‘2017/01/11 10:00’.
In reality, the command is removing all lines before ‘2017/01/11 09:00’ and after ‘2017/01/11 10:00’ (including lines with ‘2017/01/11 10:00’).

You need to modify the command to match your log file and your needs.

Bash – How to return a value in a function

Here are some ways to return a value in a function in a Bash script:

1. Strings

function foo()
{
    echo "true"
}

retval=$(foo)

if [ "$retval" == "true" ];
then
     echo "true"
fi

2. Exit status

function foo()
{
    return 0
}

foo
retval=$?

if [ $retval == 0 ];
then
     echo "okay"
fi

3. Shared variable

retval=-1

function foo()
{
    retval=0
}

foo

if [ "$retval" == 0 ]
then
     echo "okay"
fi

Adapted from: http://stackoverflow.com/questions/8742783/returning-value-from-called-function-in-shell-script