I have a script where I get a filename as input and do some processing with the file that I got as input.
Requirement:
Now I have a requirement where I need to check the following:
If either of this goes wrong, the script should pop out a warning message.
I tried searching the internet but did not get an answer. Any help is appreciated.
Below is the sample code:
#! /bin/ksh
echo "Enter the File : \c"
read filename
if [ -f $filename ]; then
Check the owner AND Permissions of the file ----> Need to code this!!!
if [ permissions are OK ]; then ----> i.e. permissions is as mentioned above
do processing
else
echo "ERROR"
fi
fi
#!/bin/sh
echo -n "File: "
read file
if [ -f $file ]; then
if [ `ls -l $file | awk '{print $3'}` = "$USER" ] && \
[ `ls -l $file | cut -c2` = "r" ] && \
[ `ls -l $file | cut -c5-10` = "------" ] ; then
echo "Owner of $file is YOU and you can read it."
echo "Group and Other can't read, write or execute it."
else
echo "ERROR"
exit
fi
else
echo "$file does not exist."
fi
If changing the file's mode is not a problem, a simple chmod can ensure that all of your conditions are met:
if ! chmod og-rwx "$file"; then
echo "ERROR"
exit 1
fi
... do processing ...
Caveat: If root may run this script, and if the file owner must stricly match the user running the script, then a check for ownerships or a chown needs to be added, since root can chmod any other user's files. For all other unprivileged users, the single chmod is enough to verify ownership as well as permissions.
An unportable alternative, if you system has one, is the stat command.