Вопрос

cd .. goes one folder up.

Is there a (one-line) command to go n folders up?

Это было полезно?

Решение

You sure can define a function to do that:

$ go_up() { for i in $(seq $1); do cd ..; done }
$ go_up 3 # go 3 directories up

Другие советы

I am not aware of any command that does that, but it is easy to create one yourself. For example, just add

cdn() {
  for ((i=0;i<${1-0};i++))
  do
    cd ..
  done
}

in your ~/.bashrc file, and after you create a new shell you can just run

cdn N

and you will move up by N directories

All right, another really funny answer, that is really a one-liner, to go up 42 parent directories:

cd $(yes ../|head -42|tr -d \\n)

Same as gniourf_gniourf's other answer, it's cd - friendly (and it's just a couple characters longer than the shortest answer).

Replace 42 with your favorite number.


Now that you understood the amazing power of the wonderful command yes, you can join the dark side and use the evil command eval, and while we're at it we can use the terrible backticks:

eval `yes 'cd ..;'|head -42`

This is so far the shortest one-liner, but it's really bad: it uses eval, backticks and it's not cd - friendly. But hey, it works really well and it's funny!

you can use a singleline for loop:..

for i in {1..3}; do cd ../; done

replace the 3 with your n

for example:

m@mariachi:~/test/5/4/3/2/1$ pwd
/home/m/test/5/4/3/2/1

m@mariachi:~/test/5/4/3/2/1$ for i in {1..3}; do cd ../; done

m@mariachi:~/test/5/4$ pwd
/home/m/test/5/4

...however I don't think it will be much faster than typing cd and .. then hitting tab for each level you want to go up!! :)

How often do you go up more than five levels? If the answer is Not too often I suggest you place these cd - friendly aliases in your profile:

alias up2='cd ../..'
alias up3='cd ../../..'
alias up4='cd ../../../..'
alias up5='cd ../../../../..'

Advantages

  • No bashims, no zshisms, no kshisms.
  • Works with any shell supporting aliases
  • As readable and understandable as it gets.

A funny way:

cdupn() {
    local a
    [[ $1 =~ ^[[:digit:]]+$ ]] && printf -v a "%$1s" && cd "${a// /../}"
}

How does it work?

  • We first check that the argument is indeed a number (a chain of digits).
  • We populate the variable a with $1 spaces.
  • We perform the cd where each space in a has been replaced with ../.

Use as:

cdupn 42

to go up to forty-second parent directory.

The pro of this method is that you'll still be able to cd - to come back to previous directory, unlike the methods that use a loop.

Absolutely worth putting in your .bashrc. Or not.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top