0

I'm pretty new to Bash scripting and am looking to do the following:

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. 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.

4

5 回答 5

1

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.

To debug pipelines like this, it's useful to use echo:

echo `pwd | sed -e s/\.git$//`
于 2011-01-06T18:53:09.270 回答
1
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.

于 2011-01-06T18:56:37.177 回答
1

This should work:

cd "${PWD%.*}"
于 2011-01-06T19:01:41.787 回答
0

That's what basename is for:

cd ../$(basename "$(pwd)" .git)
于 2011-01-06T19:00:11.180 回答
0

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 :)

于 2011-01-06T19:09:19.300 回答