golang - 简单实现linux上的which命令

本文提供了在环境变量$PATH设置的目录里查找符合条件的文件的方法。

实现函数

go 复制代码
import (
	"fmt"
	"os"
	"path"
	"strings"
)


// 实现 unix whtich 命令功能
func Which(cmd string) (filepath string, err error) {
	// 获得当前PATH环境变量
	envPath := os.Getenv("PATH")
	// 分割为多个路径
	path_list := strings.Split(envPath, ":")
	for _, dirpath := range path_list {
		// 判断环境变量路径是否是目录
		dirInfo, err := os.Stat(dirpath)
		if err != nil {
			return "", err
		}
		if !dirInfo.IsDir() {
			continue
		}
		// 判断命令所在的路径是否存在
		filepath := path.Join(dirpath, cmd)
		_, err = os.Stat(filepath)
		if err == nil || os.IsExist(err) {
			return filepath, nil
		}
	}
	return "", err
}

单元测试

go 复制代码
import (
	"testing"
    
	"github.com/stretchr/testify/assert"
)

func TestWhich(t *testing.T) {
	filepath, _ := Which("sh")
	assert.Equal(t, filepath, "/bin/sh")

	filepath, err := Which("xxx")
	assert.Equal(t, filepath, "")
	assert.ErrorContains(t, err, "no such file or directory")
}
相关推荐
2501_944875511 小时前
Go后端工程师
开发语言·后端·golang
理人综艺好会1 小时前
Redis学习之go-redis
redis·学习·golang
bing.shao1 小时前
Golang WaitGroup 踩坑
开发语言·数据库·golang
周杰伦_Jay2 小时前
【Go/Python/Java】基础语法+核心特性对比
java·python·golang
serendipity_hky4 小时前
【go语言 | 第3篇】go中类的封装、继承、多态 + 反射
开发语言·后端·golang·反射
Kiri霧5 小时前
Go切片详解
开发语言·后端·golang
古城小栈5 小时前
Go 与 Rust:系统编程语言的竞争与融合
开发语言·golang·rust
bing.shao5 小时前
Golang select多路复用踩坑
数据库·golang·php
raoxiaoya5 小时前
golang调用 elasticsearch 8,向量检索
开发语言·elasticsearch·golang
abcefg_h6 小时前
GO Web开发详细流程(无框架,restful风格,MVC架构)
开发语言·前端·golang