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.

  • What's this supposed to do? What do you want to achieve? – pfnuesel Jul 17 '17 at 19:28
  • 1
    Using pushd, popd and dirs to navigate directories is the most useful shorthand – flerb Jul 17 '17 at 19:49
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)/../../..
  • should it be: cd "$0/../../.." (with quotes) – Alexander Mills Jul 17 '17 at 20:15
  • this is much better than what I have – Alexander Mills Jul 17 '17 at 20:16
  • This is not equivalent in all cases. cd -P and cd -L may give different results. If way not work at all: if d1 exists but d1/d2/d3/d4 does not. – ctrl-alt-delor Jul 17 '17 at 20:43
  • That won't work because $0 is not a directory. You need to call dirname or do string processing to extract the directory part of $0. – Gilles Jul 19 '17 at 0:22
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 Jul 19 '17 at 0: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? – Arrow Jul 19 '17 at 1:44
0

You can use parameter expansion in bash:

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

or even simpler in zsh:

cd $0:h:h:h
  • This only works if $0 contains sufficiently many path components, not if it's just bar or foo/bar. – Gilles Jul 19 '17 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.