Verify file ownership in unix shell script
Posted by MarkTChristy (MarkTChristy), 16 September 2005Does anybody have a quick and dirty command that would verify the ownership of a file on Unix? I need to have a script that would be able to compare the owner of a file to a given owner. I have done it with a small script that long lists the filename, pipes it into 'grep' and checks the exit status of the command. It uses ls -al, tr, and grep. I am wondering if anyone knows a cryptic or different way to actually find this out.
Posted by admin (Graham Ellis), 16 September 2005Code:
will print out the uid of the file owner. Any better, or just substituting one odd set of commands for another odd command?
Posted by MarkTChristy (MarkTChristy), 16 September 2005That is a good one. The need is actually from another language (an Oracle DB based language). The 'other' language can spin off CLI commands, and then inquire as to the exit status. I did it like this...
ls -l <FILENAME> | tr " " ":" | cut -d: -f5 | grep <USERID>
If the command is succesful (or exit status == 0), then the file <FILENAME> is owned by <USERID>. The 'tr' and 'cut' commands were hang-overs for when I actually wanted to 'see' the owner only.
ls -l <FILENAME> | grep <USERID> would suffice also...
I was thinking that there may be a standard single unix command that would do this, but I can't find one.
Posted by admin (Graham Ellis), 17 September 2005Mark, your latter solution worries me slightly. If you have users called - say sam and samantha and a file called sample.txt .... then any file owned by samantha and the sample.txt file, whoever the owner is, will be reported as being sam's. This may NOT be a problem if all your user names are (say) employee codes of a very particular format whihc would never occur as part of a file name ....
Posted by Custard (Custard), 17 September 2005The <filename> in ls would catch the sample.txt. sam and samantha could still be a problem. Perhaps investigate egrep and anchor the start and end of the username.
But if you know that perl is installed, the perl solution (whilst not the only one) is only running 1 process instead of 4 which ought to be more efficient.
If not, how about using find...
'<filename>' if it matched or..
'cannot find <username> name' if it can't
these probably translate into return codes, I didn't check..
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: firstname.lastname@example.org • WEB: http://www.wellho.net • SKYPE: wellho