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
<code class="go">import ( "os" "path/filepath" "fmt" )</code>
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
For Each User Class:
Functions to Check Executability:
Executable by Owner:
<code class="go">func IsExecOwner(mode os.FileMode) bool { return mode&0100 != 0 }</code>
Executable by Group:
<code class="go">func IsExecGroup(mode os.FileMode) bool { return mode&0010 != 0 }</code>
Executable by Others:
<code class="go">func IsExecOther(mode os.FileMode) bool { return mode&0001 != 0 }</code>
Executable by Any:
<code class="go">func IsExecAny(mode os.FileMode) bool { return mode&0111 != 0 }</code>
Executable by All:
<code class="go">func IsExecAll(mode os.FileMode) bool { return mode&0111 == 0111 }</code>
<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>
Expected Output:
test/foo/bar/baz.txt false test/foo/bar/quux.txt true
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!