简体   繁体   中英

How to check if “s” permission bit is set on Linux shell? or Perl?

I am writing some scripts to check if the "s" permission bit is set for a particular file. For example - permissions for my file are as follows-

drwxr-s---

How can I check in bash script or a perl script if that s bit is set or not?

If you're using perl, then have a look at perldoc :

-u  File has setuid bit set.
-g  File has setgid bit set.
-k  File has sticky bit set.

So something like:

if (-u $filename) { ... }

non-perl options

Using stat

#!/bin/bash
check_file="/tmp/foo.bar";
touch "$check_file";
chmod g+s "$check_file";

if stat -L -c "%A" "$check_file" | cut -c7 | grep -E '^S$' > /dev/null; then
    echo "File $check_file has setgid."
fi

Explanation:

  • Use stat to print the file permissions.
  • We know the group-execute permission is character number 7 so we extract that with cut
  • We use grep to check if the result is S (indicated setgid) and if so we do whatever we want with that file that has setgid.

Using find

I have found (hah hah) that find is quite useful for the purpose of finding stuff based on permissions.

find . -perm -g=s -exec echo chmod g-s "{}" \;

Finds all files/directories with setgid and unsets it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM