gavd.co.uk

Frail and faltering follower of Jesus

Linux command of the day, 3 of 31 - stat

By Gavin Davies

I’m looking briefly at a Linux command every day for a month. Today: stat

I’m looking briefly at a Linux command every day for a month. Today: stat. This isn’t intended to be a tutorial, just some brief notes for fun

stat is for file status. We looked as lsof yesterda and there’s a lot of crossover here - both tools are really helpful in figuring out info about files beyond the bare basics of filename and contents.

The -s switch for “shell output” is more helpful in my view because it tells you what looking at!

$ stat readme.md
16777220 8599720013 -rw-r--r-- 1 gavin wheel 0 105 "Aug  3 06:32:39 2020" "Apr  2 14:21:27 2018" "Aug  2 07:24:06 2020" "Apr  2 14:21:27 2018" 4096 8 0 readme.md

$ stat -s readme.md
st_dev=16777220 st_ino=8599720013 st_mode=0100644 st_nlink=1 st_uid=501 st_gid=0 st_rdev=0 st_size=105 st_atime=1596432759 st_mtime=1522675287 st_ctime=1596349446 st_birthtime=1522675287 st_blksize=4096 st_blocks=8 st_flags=0

stat gives a lot of information that’s not explicit or present in ls by default:

  • st_dev : the device the file is on
  • st_ino : the inode the file is indexed at
  • st_mode : the full filesystem permissions. There’s a lot more than RWX going on with some files! There’s also things like sticky bit, and setting that takes the st_mode of my readme from 0100644 to 0101644.
  • st_link : number of hard links that exist to a file. If I create a non-symbolic ln to a file this goes up by 1.
  • st_uid / st_gid : user and group id
  • st_rdev Device number for char/block special files
  • st_size: size of the file in bytes
  • bunch of times for access, modified for the file itself, then inode last change and birth time
  • st_blksize : size of the blocks the file uses on the filesystem. In some OSs, differing block sizes can be used for different files
  • st_locks : number of blocks allocated for the file
  • st_flags : user defined flags

Some good use cases for stat include:

  1. Figuring out how many blocks a file uses
  2. Seeing how many hard links a file has
  3. Really digging in to the permissions, including special permissions like the sticky bit

Another neat feature is stat without a filename will give you information about the file descriptor for stdin

$ stat
984357888 883 crw--w---- 1 gavin tty 268435456 0 "Aug  3 06:59:16 2020" "Aug  3 06:59:16 2020" "Aug  3 06:59:16 2020" "Jan  1 01:00:00 1970" 131072 0 0 (stdin)