繁体   English   中英

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

[英]Bash: cd to directory provided by program output

我有一个简短的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 $@的输出~/marker.sh go $@

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

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

我认为这意味着外壳程序将整个别名解析为一个字符串。

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

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

如果重要,我正在iTerm 1.0.0.20130624中运行OSX 10.9。

编辑:我知道脚本内的cd-ing将无法正常工作 ,这就是为什么我试图使用程序返回正确的路径并使用内置别名系统执行目录的实际更改的原因。

您需要一个函数,而不是别名:

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

别名不带任何争论。 它们只是就地扩展,而参数会在别名扩展为任何对象之后发生。

(除非函数不能适应您的期望,否则您应该始终偏向别名而不是别名。)

使用函数,而不是别名或外部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。 对你太坏了。 但是,这可能对使用现代Shell的其他人有用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM