Bash:cd到程序输出提供的目录

时间:2013-10-28 18:13:18

标签: linux macos bash shell alias

我有一个简短的shell程序,它返回一个系统路径。我想要做的是使用bash别名CD到该路径。

我理想的输出是

~$ pwd
    /home/username
~$ mark home
~$ cd /
/$ pwd
    /
/$ place home
~$ pwd
    /home/username

我有“标记”部分工作,但“地方”不是:

alias place="cd \"~/marker.sh go $@\";"

我的想法是我想要cd到~/marker.sh go $@

的输出

问题是bash将此解释为一个命令,并给出错误:

-bash: cd: ~/marker.sh go : No such file or directory
-bash: home: command not found

我假设这意味着shell正在将整个别名解析为字符串。

我尝试了别名$(),``等的shell脚本部分的各种形式的引用,但是他们要么尝试在bash start上运行脚本,要么根本不执行而只是保留一个字符串。

我正在编程这主要是为了学习bash命令,但我无法弄清楚这一部分!

我在iTerm 1.0.0.20130624中运行OSX 10.9,如果这很重要的话。

编辑:我理解cd-ing inside a script won't work,这就是我尝试使用我的程序返回正确路径并使用内置别名系统来实际更改目录的原因。

2 个答案:

答案 0 :(得分:2)

你想要一个功能,而不是别名:

place () {
    cd $( ~/marker.sh go "$@" )
}

别名不接受争论;它们只是在原地扩展,并且在别名扩展到的任何地方之后发生了争论。

(除非该功能无法适应您想要的功能,否则您应该总是喜欢将功能添加到别名中。)

答案 1 :(得分:2)

使用函数,而不是别名或外部bash脚本!

在您的.bashrc或由其提供的任何文件或您将手动提供的任何文件中,放置此完全可用的脚本!

declare -A _mark_dir_hash

mark() {
   [[ -z $1 ]] && { listmarks; return 0; }
   if [[ -n ${_mark_dir_hash[$1]} ]] && [[ $1 != ${_mark_dir_hash[$1]} ]]; then
       echo "Mark $1 was already set to ${_mark_dir_hash[$1]}... replaced with new mark"
   fi
   _mark_dir_hash[$1]=$(pwd)
}

place() {
   [[ -z $1 ]] && { echo >&2 "You must give a mark name to go to!"; return 1; }
   [[ -z ${_mark_dir_hash[$1]} ]] && { echo >&2 "Mark $1 unknown!"; return 1; }
   cd "${_mark_dir_hash[$1]}"
}

listmarks() {
   [[ -z ${!_mark_dir_hash[@]} ]] && { echo "No marks!"; return 0; }
   for i in "${!_mark_dir_hash[@]}"; do
      printf '%s --> %s\n' "$i" "${!_mark_dir_hash[@]}"
   done
}

removemark() {
   [[ -z $1 ]] && { echo >&2 "You must give a mark name to remove!"; return 1; }
   unset _mark_dir_hash[$1]
}

clearmarks() {
   _mark_dir_hash=()
}
哈,我刚刚意识到你在Mac上,所以你可能会遇到一个不支持关联数组的古老版本的bash。对你太坏了。然而,这可能对使用现代贝壳的其他人有用!