2

I have a variable which contains the current directory including several parents. For example:

$ pwd
/Users/simont/repositories
$ echo $current
~/repositories

I can strip everything except the current directory from this question:

onlycurrent=${$(current)##*/}

I want to do the opposite: remove the current dir from this variable (so that it only contains ~/). How can I do this?

Community
  • 1
  • 1
simont
  • 68,704
  • 18
  • 117
  • 136

2 Answers2

2

Using dirname you can strip off the last directory:

$ current="~/repositories"
$ echo $current
~/repositories
$ dirname $current
~

Admittedly this does not save the / character to the right of ~.

If you wish to do this simply using bash you could do:

$ echo ${current%/*}
~

Which strips off everything after the last / (including the / itself).

imp25
  • 2,327
  • 16
  • 23
0

This does not solve you problem in full generality, but you may want to look at dirname (and basename)

/home/or..product/oracle10 >pwd
/home/oracle/product/oracle10

/home/or..product/oracle10 >dirname `pwd`
/home/oracle/product

/home/or..product/oracle10 >basename `pwd`
oracle10

BTW: dirname does not really care if the returned string is really a directoy, it works on arbitrary strings.

/home/or..product/oracle10 >dirname "/foo/bar/baz"
/foo/bar
Martin Drautzburg
  • 5,143
  • 1
  • 27
  • 39