Going n folders up with a terminal command?

≯℡__Kan透↙ 提交于 2019-12-10 17:55:35

问题


cd .. goes one folder up.

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


回答1:


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



回答2:


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




回答3:


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!




回答4:


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!! :)




回答5:


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.



回答6:


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.



来源:https://stackoverflow.com/questions/17381145/going-n-folders-up-with-a-terminal-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!