How to test if a file is executable by its owner ** not necessarily me **

user1011471 Source

This is not a duplicate question.

Assume I have

  1. the full path
  2. to a regular file named target
  3. that might be owned by some other user.
  4. and the environment may be stripped down (busybox with very little enabled)

In a shell script, how can I test whether this file is executable by its owner when I might not be its owner? Imagine that my program's purpose is to check if everything is set up nicely for other things to run (since the environment may have been ruined by other users) and it's looking in a particular directory to make sure the owners of every file have permission to execute their file.

This is a professional context, not homework.

Any solution I will use needs to cover all kinds of old Linux environments that I had no hand in setting up (so they could be missing things you'd normally expect like which or some options on find etc).

However, this question might be useful for others who don't face that limitation so I do appreciate other solutions that require more complete or modern environments.

[ -x "$path" ] only tells me if I can execute it.

ls -l "$path" and checking if the fourth character is x seems too fragile: -rwxrw-rw- 1 otheruser group 26 Jun 13 10:57 target

ls -F "$path" and checking if it ends in * seems a little better: target* The one environment I tested does take into account who the actual owner is... But this does not feel like the best way...



answered 4 months ago Athanasios Emmanouilidis #1

ls -l "$path" and check the first group of permissions (owner permissions). If there is an x in it then the file is executable by its owner.

answered 4 months ago jeremysprofile #2

permissions=$(stat -c "%a" target)
permissions=$(( ${permissions: -3: 1} % 2 ))

stat gives you file permissions in octal. Then we need just the character for the owner's permissions (technically third from the right, not the first character), and then need to check if it's odd (executable in octal is the 1 bit).

If permissions is 1, it's executable by the owner. If it's 0, it's not.

Older environments might require arithmetic expressions instead:

permissions=$(stat -c "%a" $target)
if [ $((0$permissions & 0100)) -ne 0 ]; then
    # executable by owner
    # not executable by owner

answered 4 months ago Brandon Miller #3

You could use find, if you don't want to parse the output of something:

if find ${path} -prune -perm -u+x | grep -q ''; then
  echo "Executable by owner"
  echo "Not executable by owner"

The -perm option let's you check if it's executable by the user (owner) and the -prune option prevents descending in to a directory if ${path} is a directory so we can just check the given path by itself.

comments powered by Disqus