1

背景:

这个问题是关于在 bash 脚本或别名中使用 cd 命令。

这里有一个相关的 SO 问题:Why doesn't "cd" work in a bash shell script?

问题:

假设您有一个名为“foopath”的 bash 程序,当您传入一个参数时,它会将一个目录的路径发送到标准输出,例如,

  $> /usr/bin/foopath 1998      ## returns /some/long/path/here/1998
  $> /usr/bin/foopath 80817     ## returns /totally/different/path/80817/files

foopath 程序只是进行查找并根据用户传入的参数返回它可以找到的最接近的匹配路径。

问题:

1)您将如何在 .bash_profile 中构造函数和别名,以便用户可以:

  • 1a)类型foo 1998foo 80817(foopath命令缩短目标)
  • 1b)使用cd foo 1998cd foo 80817更改目录(更改目录目标)
  • 1c)从命令提示符更改目录(不仅仅是子shell-only目标)

陷阱

由于上面 1c 中的目标,这个看似简单的任务被证明是繁琐的。换句话说,函数/别名应该可以交互使用,正如相关 SO 帖子中的示例所示,为什么“cd”不能在 bash shell 脚本中工作?.

4

2 回答 2

1

1a)

foo () {
    cd "$(foopath $1)"
}

1b)

cd () {
    case $1 in     
      (foo) builtin cd "$(foopath $2)";;
      (*)   builtin cd "$@";;
    esac
}

1c) 1a) 和 1b) 都可以交互使用。

于 2013-05-13T11:01:26.890 回答
1

解决方案可能是

  1. 通过将脚本改为函数

    function script() 
    {
         cd "$(foopath "$*")"
    }
    
  2. 通过使用source script.sh(or . script.sh) 代替,因此脚本在调用 shell 中运行

于 2013-05-13T11:02:20.960 回答