0

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

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

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

4

4 に答える 4

4

したがって、1つの問題は、パスを引用符で囲むと~、シェルがパスをに渡す前にそれを展開しないことcdです。$HOME代わりに使用するか~/、引用符の外側に配置することで、これを修正できます。

また、に$DIR基づいて条件付きで設定する必要はなく、および$1を使用する必要もありません。パスで直接使用してください。空の場合、そのディレクトリコンポーネントは空になり、の引数としてディレクトリだけが残ります。sedxargs$1Working Branchescd

単に

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

わずかに短いが明確ではないように、動作するはずです

function projects () {
  cd ~/"Projects/Working Branches/$1"
}
于 2010-09-21T19:21:36.777 に答える
2

多分あなたはこれを過剰に設計しています:

cd "~/Projects/Working Branches/"
cd "$DIR"

sedただし、コマンドの目的がよくわからないので、何か不足している可能性があります。

于 2010-09-21T18:25:51.133 に答える
2

問題は、チルダ展開がシェル (bash) によって実行され、xargs も cd も OS もこれを実行しないことです。これが、~ を含むディレクトリが不明な理由です。~ の代わりに $HOME を使用することもできますが、二重引用符で囲まれた作業ディレクトリに置き換えられるか、引用符の外側にチルダを配置することもできます (つまり、~/"...")。

さらに、cd は別のプロセスで実行されるため、xargs を指定して cd を呼び出しても作業ディレクトリは変更されません。代わりに cd ~/"Projects/Working Branches/" を使用することを検討してください。

于 2010-09-21T19:09:01.243 に答える
1

xargs and cd does not work together in my bash. I think it's because xargs want an application and cd is a built-in function in the bash shell.

try echo "Projects" | xargs cd in your home directory to se if this is the case.

Another problem is that ~ doesn't get expanded as you think by echo. Try using the full path instead. Or use backticks to expand the ~

echo ´echo ~/`"Projects/Working Branches/$DIR"
于 2010-09-21T18:14:17.550 に答える