Script in UNIX (Bash) to determine if the user is the owner of a file

3

1

Something that would take any number of arguments, where each argument would be a path to a file or directory. If the user does own a particular path then it should check it to see if the path represents a normal file AND if that file is executable. If it is, then your script should execute/run the file.

Thanks for any help I've been trying different things for too long and I'm frustrated.

roger34

Posted 2009-10-07T12:39:26.307

Reputation:

Homework question? Regardless, you should really show what you've tried so far. – Paused until further notice. – 2009-10-07T13:34:40.133

Answers

4

magic() {
    for p in "$@"; do
        [ -O "$p" -a -x "$p" ] && /bin/sh "$p"
    done
}

read 'man test' to see what the checks do.

akira

Posted 2009-10-07T12:39:26.307

Reputation: 52 754

4Illegible showing off. – Tadeusz A. Kadłubowski – 2009-10-07T14:22:08.147

@tkadlubo: indeed. part to blame is display of <code> enclosed stuff here on superuser. – akira – 2009-10-07T14:28:17.340

3

The -O test checks if the current user is the owner of a file or folder.

if [ -O "$FILENAME" ]; then echo 'Owned!'; else echo 'Nope!'; fi

See list of file test operators (and how to do tests in general.)

Using stat on *nix for this purpose is tricky to do portably due to differences between platforms.

Qwertie

Posted 2009-10-07T12:39:26.307

Reputation: 151

3

To get current user id you do:

id -u

to get owner of file, you do:

stat -c "%u" file.name

to test if one value is the same as the other you do:

if [ "$first" -eq "$second" ]
then
    ....
fi

user7385

Posted 2009-10-07T12:39:26.307

Reputation:

...and for looping on arguments consider shift... – dmckee --- ex-moderator kitten – 2009-10-07T13:21:28.683

1Note that on OSX (and perhaps other BSD-alikes) you need to use stat -f "%u" file.name instead... – Irongaze.com – 2013-05-16T14:36:44.557