简体   繁体   English

Bash:在目录“ directory_name.git”中,如何将CD刻录到“ ../directory_name”?

[英]Bash: in directory `directory_name.git`, how to cd to `../directory_name`?

I'm pretty new to Bash scripting and am looking to do the following: 我对Bash脚本还很陌生,并且正在考虑执行以下操作:

The script's pwd is "/a/b/c/directory_name.git/" and I'd like to cd to "../directory_name" where directory_name could be anything. 脚本的密码是“ /a/b/c/directory_name.git/”,我想用cd到“ ../directory_name”,其中directory_name可以是任何东西。 Is there any easy way to do this? 有没有简单的方法可以做到这一点?

I'm guessing I'd have to put the result of pwd in a variable and erase the last 4 characters. 我猜我必须将pwd的结果放入一个变量中并删除最后4个字符。

Try: 尝试:

cd `pwd | sed -e s/\.git$//`

The backticks execute the command inside, and use the output of that command as a command line argument to cd . 反引号内执行该命令,并使用命令的输出作为命令行参数cd

To debug pipelines like this, it's useful to use echo : 要调试这样的管道,使用echo很有用:

echo `pwd | sed -e s/\.git$//`
tmpd=${PWD##*/}
cd ../${tmpd%.*}

or perhaps more simply 或更简单

cd ${PWD%.*}

Test 测试

$ myPWD="/a/b/c/directory_name.git"
$ tmpd=${myPWD##*/}
$ echo "cd ../${tmpd%.*}"
cd ../directory_name

*Note: $PWD does not include a trailing slash so the ${param##word} expansion will work just fine. *注意:$ PWD不包含斜杠,因此${param##word}扩展会很好用。

这应该工作:

cd "${PWD%.*}"

这就是基basename的用途:

cd ../$(basename "$(pwd)" .git)

Didn't expect to get so many answers so fast so I had time to come up with my own inelegant solution: 没想到这么快就能得到这么多答案,所以我有时间想出自己的优雅解决方案:

#!/bin/bash

PWD=`pwd`
LEN=${#PWD}
END_POSITION=LEN-4
WORKING_COPY=${PWD:0:END_POSITION}

echo $WORKING_COPY
cd $WORKING_COPY

There's probably one above that's much more elegant :) 上面可能有一个更优雅了:)

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

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