0

I have this:

cd $(dirname $(dirname $(dirname "$0"))) &&

which will cd to project root.

Is there shorthand for this somehow, where I can just be like:

cd 3 &&  # not quite, but you get the idea

or whatever, I mean why not you know?

Maybe a command like so would be ideal:

cdx 3 &&

since cd has no idea that 3 is not a file or directory.

3 Answers3

1

You do know that cd .. takes you to the parent directory? So, if I understand your question correctly, you could use:

cd $(dirname $0)/../../..
Bob Eager
  • 3,600
1

Define this function:

dirx(){ a=$0;for((i=0;i<$1;i++));do a=${a%/*};done;cd "$a"; }

And do:

$ dirx 3
  • This only works if $0 contains sufficiently many path components, not if it's just bar or foo/bar. – Gilles 'SO- stop being evil' Jul 19 '17 at 00:23
  • @Gilles It fails gracefully to the string provided. If it is just bar, it results on cd bar. If bar doesn't exist, it provides a clear error mesage: bash: cd: bar: No such file or directory. What is not robust enought for you? –  Jul 19 '17 at 01:44
0

You can use parameter expansion in bash:

cd "${0%/*/*/*}"

or even simpler in zsh:

cd $0:h:h:h
jimmij
  • 47,140