How to check if a file or directory is hidden in Go

Checking the hidden status of a file or directory is dependent on the operating system that the code is running on. For Linux/Unix-based systems such as macOS, all you need to do is check the first character of the file. On Windows, it’s a little more complicated than that

In Linux and Unix-like operating systems, any file or folder that starts with a dot character (such as .local or .bashrc), commonly called a dotfile, is treated as hidden by file managers and commands such as ls. This makes it really easy to detect a hidden file in Go source code:

func isHidden(filename string) bool {
	if filename[0:1] == "." {
		return true

	return false

All you need to do is check if the first character of the filename corresponds to a .. If so, the file is hidden. Otherwise, it’s not.

For Windows, the hidden status of a file or directory is not determined by whether or not it starts with a dot character. Rather, it’s determined by a Hidden file attribute which is manipulated through the attrib command. You can also view and set the status of this attribute through the file properties dialog.

Windows properties dialog

Therefore, checking if a file is hidden in Windows involves checking the status of the Hidden attribute as shown below:

// +build windows

package main

import "syscall"

func isHidden(filename string) (bool, error) {
	pointer, err := syscall.UTF16PtrFromString(filename)
	if err != nil {
		return false, err

	attributes, err := syscall.GetFileAttributes(pointer)
	if err != nil {
		return false, err

	return attributes&syscall.FILE_ATTRIBUTE_HIDDEN != 0, nil

When using the code, make sure you set build constraints on the files where these functions are placed so that they will only be included in the build for the relevant operating system. For example, you can use the line below in the file where the linux/unix version of the isHidden function is placed so that it’s not included in any build targetting Windows.

// +build !windows

Thanks for reading, and happy coding!