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

后端 未结 2 566
悲&欢浪女
悲&欢浪女 2021-01-23 09:38

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---


        
相关标签:
2条回答
  • 2021-01-23 10:01

    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) { ... }
    
    0 讨论(0)
  • 2021-01-23 10:08

    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.

    0 讨论(0)
提交回复
热议问题