Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Thursday, June 24, 2010

Prevent vi from opening files for which you do not have read permission

Found an annoying thing in one of the new servers I was playing around. It generated some log files as root and permissions of 600 and others as the designated user. Now the problem is that when I open log files with 600 permission in vi it happily opens up but, shows a blank buffer with 'Permission Denied' error. After a couple of times I got really annoyed and decided to fix it.


Attempt 1: ~/bin is ahead in the path to /usr/bin/vi so, wrote a simple script to check for file permissions.
#!/bin/sh
if [ -e $1 -a ! -r $1 ]; then
  echo No read permission for $1
  exit 1
fi
/usr/bin/vi $1
But, sadly that did not cut it
Attempt 2: Stuffed the above in an alias. I'll leave as an exercise for you to figure out what happens
Attempt 3: Then converted the same logic to a shell function called vi and w00t! it worked :)
vi() {
  if [ -e $1 -a ! -r $1 ]; then
    echo No read permission for $1
  else
    /usr/bin/vi $1
  fi
}