linux shell go to语句,用Go语言写一个简单的shell

> cd /

> ls

LICENSE

main.go

main_test.go

很明显这不是我根目录下的内容。为什么cd命令没有起作用?如果你知道真实路径,那就非常简单了(https:/ /stackoveryow.com/a/38776411)cd程序是shell一个内建的命令。

再一次,我们需要修改execInput函数。在Split函数之后,我们需要把存储在args[0]的第一个变量(执行的命令)进行一个状态转换。当命令为cd时,我们检查后面是否有变量,如果没有,我们不能改变目录到指定目录(在大多数其他shell中,需要改变目录到根目录下)。如果后面有变量arg[1](存储到路径中),我们可以使用os.Chdir(args[1])改变目录。在这个程序块的最后,我们返回execInput 函数以停止进一步的内键命令执行。

由于这很简单,我们只需要在cd块的右面增加一个 built-in exit 命令,就可以停止我们的shell(另一个选择是使用CTRL-C)

// Split the input to separate the command and the arguments.

args := strings.Split(input, " ")

// Check for built-in commands.

switch args[0] {

case "cd":

// 'cd' to home dir with empty path not yet supported.

if len(args) < 2 {

return errors.New("path required")

}

err := os.Chdir(args[1])

if err != nil {

return err

}

// Stop further processing.

return nil

case "exit":

os.Exit(0)

}

当然,随后的输出看起来像我的跟目录了。

> cd /

> ls

Applications

Library

Network

System

综上,我们写了一个简单的shell。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值