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.

Olivier Lalonde
  • 19,423
  • 28
  • 76
  • 91

5 Answers5

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$//`
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
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.

SiegeX
  • 135,741
  • 24
  • 144
  • 154
1

This should work:

cd "${PWD%.*}"
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
0

That's what basename is for:

cd ../$(basename "$(pwd)" .git)
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • `basename $PWD` is equivalent to the native shell syntax `${PWD##*/}` but with the added benefit of not having to call an external command – SiegeX Jan 06 '11 at 19:06
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 :)

Olivier Lalonde
  • 19,423
  • 28
  • 76
  • 91