Archive for the ‘ Bash ’ Category

Avoid race condition for file creation

race condition in the common lock on file? – Stack Overflow.

A possible solution to this is to use IO redirection and bash’s noclobber mode, which won’t redirect to an existing file. We can use something similar to:

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
   # BK: this will cause the lock file to be deleted in case of other exit
   trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT

   # critical-section BK: (the protected bit)

   rm -f "$lockfile"
   trap - INT TERM EXIT
else
   echo "Failed to acquire lockfile: $lockfile."
   echo "Held by $(cat $lockfile)"
fi

Disk I/O stats from /proc/diskstats

Disk I/O stats from /proc/diskstats

cat /proc/diskstats | grep 'sda '
   8    0 sda 2461810 61427 148062742 6482992 660009 1544934 67900384 45642376 0 7162961 52128751

Field 1 — # of reads issued
Field 2 — # of reads merged, field 6 — # of writes merged
Field 3 — # of sectors read
Field 4 — # of milliseconds spent reading
Field 5 — # of writes completed
Field 7 — # of sectors written
Field 8 — # of milliseconds spent writing
Field 9 — # of I/Os currently in progress
Field 10 — # of milliseconds spent doing I/Os
Field 11 — weighted # of milliseconds spent doing I/Os

Linux set date and time on command line

Linux Set Date and Time From a Command Prompt.

How can I set the system date and time from the command prompt (bash shell)? I don’t have GUI installed and I am login over ssh session. How can I set date under Linux operating systems?

Use the date command to display the current date and time or set the system date / time over ssh session. You can also run the date command from X terminal as root user.

This is useful if the Linux server time and/or date is wrong, and you need to set it to new values from the shell prompt.

You must login as root user to use date command.

Linux Set Date

Use the following syntax to set new data and time:

date --set="STRING"

For example, set new data to 2 Oct 2006 18:00:00, type the following command as root user:

# date -s "2 OCT 2006 18:00:00"

OR

# date --set="2 OCT 2006 18:00:00"

You can also simplify format using following syntax:

# date +%Y%m%d -s "20081128"

Linux Set Time

To set time use the following syntax:

# date +%T -s "10:13:13"

Where,

  • 10: Hour (hh)
  • 13: Minute (mm)
  • 30: Second (ss)

Use %p locale’s equivalent of either AM or PM, enter:

# date +%T%p -s "6:10:30AM"
# date +%T%p -s "12:10:30PM"