Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Thursday, July 10, 2014

flock - Manage locks from shell scripts

Only one running instance of a script:

flock -n /var/lock/lock_file.lock script.sh


Thursday, December 20, 2012

Find files in a particular directory which are older than 30 min

My solution to the following problem:
How can I find files in a particular directory which are older than 30 min? I am not able to use several functions like -mmin, -stat, date -r . And I cant create a dummy file with touch command also,as it is to be done in a production environment.
Posted in: http://unix-simple.blogspot.com/2008/01/awkgawk-shell-script-question_31.html


#!/bin/bash

# Current time in seconds since the EPOCH
CURRENT_TIME=$(date +%s)

# 30 minutes in seconds
OFFSET=$((30 * 60))

# The record delimiter
IFS=$'\012'

# The Linux ls
for LINE in $(ls -l --time-style=+%s)
do
        FILE_TIME=$(echo ${LINE} | sed 's/[ ]\+/ /g' | cut -d " " -f 6)
        FILE_NAME=$(echo ${LINE} | sed 's/[ ]\+/ /g' | cut -d " " -f 7)
        TIME_DIFF=$((CURRENT_TIME - FILE_TIME))

        # Avoiding that annoying total count in ls -l
        if [ -n "${FILE_NAME}" ]
        then
                if [ ${TIME_DIFF} -gt ${OFFSET} ]
                then
                        echo "${FILE_NAME} ${FILE_TIME} ${CURRENT_TIME} ${TIME_DIFF}"
                fi
        fi
done

##END##

Wednesday, October 5, 2011

Previous date in bash

Sometimes I need the previous date in my scripts:

DATE=$(date +%Y%m%d --date=-1day)

For 10/5/2011 DATE = 20111004

$ date --version
date (GNU coreutils) 6.10

Tuesday, April 13, 2010

Number of days in current Month in UNIX shell

cal | grep -v '[A-Za-z]' | wc -w

Last Sunday of the Month in UNIX shell

cal | grep '^[23]' | tail -1 | cut -d' ' -f1

Several months later I don't remember why the grep part?

cal | tail -1 | cut -d' ' -f1


AWK version:



#!/bin/bash


cal | awk '
    { last = $1 }
END { print last }'


##END##