我在这个bash函数中做错了什么? [英] What am I doing wrong in this bash function?

查看:60
本文介绍了我在这个bash函数中做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个转到特定目录的函数,如果指定了单个参数,则将其添加到目录字符串中.但是无论我尝试什么,我都无法使它工作,bash总是报告X不是目录,即使我将它复制/粘贴到新的命令行也可以从那里工作.

I'm trying to create a function that goes to a specific directory, and if a single argument is specified add that to the directory string. But no matter what I try I can't get it to work and bash always reports that X is not a directory even though if I copy/paste it to a new command line it works from there.

function projects ()
{
  DIR=
  if [ -n "$1" ]
  then
    DIR=$1
  fi
  echo "~/Projects/Working Branches/$DIR" | sed 's/ /\\&/g' | xargs cd
}    

-

$ projects Parametric\ Search\ API
/usr/bin/cd: line 4: cd: ~/Projects/Working Branches/Parametric Search API: No such file or directory
$ projects "Parametric Search API"
/usr/bin/cd: line 4: cd: ~/Projects/Working Branches/Parametric Search API: No such file or directory

我还尝试将sed regexp修改为 s//\\\\\\&/g ,这会产生似乎是正确转义的字符串,但其结果完全相同错误

I've also tried modifying the sed regexp to s/ /\\\\\\&/g which produces what appears to be a properly escaped string, but results in the same exact error

$ projects Parametric\ Search\ API
/usr/bin/cd: line 4: cd: ~/Projects/Working\ Branches/Parametric\ Search\ API: No such file or directory
$ projects "Parametric Search API"
/usr/bin/cd: line 4: cd: ~/Projects/Working\ Branches/Parametric\ Search\ API: No such file or directory

最后,我尝试将 $ DIR 包围在我能想到的所有引号组合中,但到目前为止还算不上运气.

An finally I've tried surrounding $DIR with every combination of quotes I can think of, but no luck so far.

推荐答案

所以,一个问题是,如果您引用的路径中带有,则在将其传递给shell之前,shell不会对其进行扩展 cd .您可以改用 $ HOME 来解决此问题,或者将〜/放在引号之外.

So, one problem is that if you quote a path with ~ in it, the shell will not expand that before passing it into cd. You can fix this by using $HOME instead, or by putting the ~/ outside of the quotes.

此外,您不需要基于 $ 1 有条件地设置 $ DIR ,也不需要使用 sed xargs .只需在路径中直接使用 $ 1 即可;如果为空,则该目录组件将为空,仅留下 Working Branches 目录作为 cd 的参数.

Also, you don't need to conditionally set $DIR based on $1, nor do you need to use sed and xargs. Just use $1 directly in your path; if it's empty, that directory component will be empty, leaving you with just the Working Branches directory as an argument to cd.

简单

function projects () {
  cd "$HOME/Projects/Working Branches/$1"
}

应该有效,稍短但不太清晰的

should work, as would the slightly shorter but less clear

function projects () {
  cd ~/"Projects/Working Branches/$1"
}

这篇关于我在这个bash函数中做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆