2

I'm trying to have a shortcut for going back a few dirs. Something like "cd ...." == "cd <number of dots - 1> * '../'"

  1. I tried doing alias '...'='../..' && cd ... but got "No such file or directoy"
  2. I then tried doing alias '...'='../..' but got "invalid alias name"
  3. I guess I can create a function: function bla { for i in $(seq $(($1 - 1))); do cd ../; done; }; bla 3 but that seems less elegant (and also I cd ../ one in a time which is bad (cd - won't have the desired effect for example) but I can concat the strings and only cd at the end)

My questions are: How to solve (1) & (2) and is there a neater way for this?

  • I did a function doing almost exactly what you ask for, you only need the cd function, but it is nice with bash-completion. –  Jan 21 '21 at 11:54
  • Neither of the suggested duplicates seem to address the actual issue here: creating aliases with multiple dots (especially not arbitrarily many, as my answer does). – Ryan M Jan 21 '21 at 13:57

2 Answers2

5

I'd recommend

alias '...'='cd ../..'

With that, you can simply type ... and go up two directories (even easier than cd ...!)

You can even make a whole set of them:

alias '..'='cd ..'
alias '...'='cd ../..'
alias '....'='cd ../../..'
alias '.....'='cd ../../../..'

...and so on

Alternately, if you want to skip all that typing, this will create all the aliases up to 100 directories:

alias_str=".."
cmd_str="cd .."
for i in $(seq 1 100);
do
    alias ${alias_str}="$cmd_str"
    alias_str="$alias_str."
    cmd_str="$cmd_str/.."
done
Ryan M
  • 153
3

Use a function like this:

...() { 
  b=".."
  # check that the argument is a number
  if [[ ! "$1" =~ ^[0-9]*$ ]]; then
    echo "Bad argument."
  else
    # if no arguments, or it is 1, just back 1 dir
    if [[ $# -eq 0 || "$1" -eq 1 ]]; then 
      cd ..
    else 
      for i in $(seq 1 "$1"); do
        b+="/.."
      done
      cd "$b"
    fi
  fi
}

So you pass the argument of how many dirs you want to go back. Example:

$ cd /home/user/Foo/bar

/home/user/Foo/bar$ ... 2

/home/user/$