Checking file owner permissions

2020-02-26 03:07发布

问题:

I'm trying to test if a file has the execute bit set for the owner in bash script.

I know if [ -x filename ] checks for execute permission for the User running the statement but i need to know if the owner has it. Is there a way to specify owner?

回答1:

You can use stat to get the file permissions, and parse them with another command to get the character you want.

stat -c %A someFile

Returns something like:

-rw-rw-r--

EDIT: Here you go:

stat -c %A someFile | sed 's/...\(.\).\+/\1/'

Returns either - or x if the owner has execute.

EDIT 2: For completion's sake:

if [ `stat -c %A someFile | sed 's/...\(.\).\+/\1/'` == "x" ] 
then
  echo "Owner has execute permission!"
fi

EDIT 3: If you prefer numerical permissions:

stat -c %a /path/to/a/file will output 600 or 700 or whatever 3 digit base-8 number.