≡ Menu

shell variable

A quick question from my mail bag:

How do I display or get the date when a file was last time accessed?

The best and simplest way is to use stat command. It displays file or file system status such as:

=> File size

=> File type

=> Inode number

=> UID/GID

=> File access , modify and creation time etc.

stat command example

$ stat /etc/passwd
Output

  File: `/etc/passwd'
  Size: 2453            Blocks: 8          IO Block: 4096   regular file
Device: 806h/2054d      Inode: 25298826    Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2007-08-06 04:45:18.000000000 -0500
Modify: 2007-07-17 16:25:12.000000000 -0500
Change: 2007-07-17 16:25:12.000000000 -0500

Display file system status

You can display file system status instead of file status. For example, display status for / file system:
$ stat -f /
Output:

  File: "/"
    ID: 0        Namelen: 255     Type: ext2/ext3
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 32161831   Free: 30458361   Available: 28798245
Inodes: Total: 33226752   Free: 33135357

stat command and shell scripts

You can use stat in a shell script. It supports -c option. By default it shows all information about file. Use -c option to specify FORMAT instead of the default. For example store access time in a shell variable:

ATIME=$(stat -c "%x" /etc/passwd)
echo $ATIME

See the stat command man page for full details for the valid format sequences for files:
man stat

A shell variable may be assigned to by a statement using following syntax:
var=value

If value is not given, the variable is assigned the null string. In shell program it is quite useful to provide default value for variables. For example consider rsync.sh script:
#!/bin/bash
RSRC=$1
LOCAL=$2
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL

This script can be run as follows:
$ ./rsync.sh /var/www .
$ ./rsync.sh /home/vivek /home/vivek

It will sync remote /home/vivek directory with local /home/vivek directory. But if you need to supply default values for a variable you can write as follows:

#!/bin/bash
RSRC=$1
LOCAL=$2
: ${RSRC:="/var/www"}
: ${LOCAL:="/disk2/backup/remote/hot"}
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL

: ${RSRC:="/var/www"} ==> this means if the variable RSRC is not already set, set the variable to /var/www. You can also write same statement with following code:

if [ -z "$RSRC" ]
then
   RSRC="/var/www"
fi

You can also execute a command and set the value to returned value (output). For example if the variable NOW is not already set, execute command date and set the variable to the todays date using date +"%m-%d-%Y":

#!/bin/bash
NOW=$1
....
.....
: ${NOW:=$(date +"%m-%d-%Y")}
....
..