> 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。