How to Determine if a Go File is Executable?

Linda Hamilton
Release: 2024-11-04 00:18:02
Original
949 people have browsed it

How to Determine if a Go File is Executable?

How to Determine Executable File Status in Go

Given an os.FileInfo instance, you may need to check if a file is executable in Go. This requires deciphering the permission bits from os.FileInfo.Mode().

Test Case:

#!/usr/bin/env bash
mkdir -p test/foo/bar
touch test/foo/bar/{baz.txt,quux.sh}
chmod +x test/foo/bar/quux.sh
Copy after login
<code class="go">import (
    "os"
    "path/filepath"
    "fmt"
)</code>
Copy after login

Solution:

The file's executability is determined by the Unix permission bits stored in os.FileMode.Perm(). These bits form a 9-bit bitmask (0777 octal).

Unix Permission Bit Meaning:

rwxrwxrwx
Copy after login

For Each User Class:

  • Owner: Bitmask 0100
  • Group: Bitmask 0010
  • Others: Bitmask 0001

Functions to Check Executability:

  • Executable by Owner:

    <code class="go">func IsExecOwner(mode os.FileMode) bool {
      return mode&0100 != 0
    }</code>
    Copy after login
  • Executable by Group:

    <code class="go">func IsExecGroup(mode os.FileMode) bool {
      return mode&0010 != 0
    }</code>
    Copy after login
  • Executable by Others:

    <code class="go">func IsExecOther(mode os.FileMode) bool {
      return mode&0001 != 0
    }</code>
    Copy after login
  • Executable by Any:

    <code class="go">func IsExecAny(mode os.FileMode) bool {
      return mode&0111 != 0
    }</code>
    Copy after login
  • Executable by All:

    <code class="go">func IsExecAll(mode os.FileMode) bool {
      return mode&0111 == 0111
    }</code>
    Copy after login
<code class="go">func main() {
    filepath.Walk("test", func(path string, info os.FileInfo, err error) error {
        if err != nil || info.IsDir() {
            return err
        }
        fmt.Printf("%v %v", path, IsExecAny(info.Mode().Perm()))
    }
}</code>
Copy after login

Expected Output:

test/foo/bar/baz.txt false
test/foo/bar/quux.txt true
Copy after login

The above is the detailed content of How to Determine if a Go File is Executable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!