'How to create an alias in a shell to go to parent directories

I'm wondering how to create an alias with endless arguments for going parent directories without alias name!

Currently I have written this function to achieve it and works perfectly.

b() {
  list=$1
  for (( i=0; i<${#list}; i++ )); do
    cd ..
  done
}

You can use it like b .. or b ... or b .

The thing I want is that to use it without "b", just dots! How can we make it dynamically?

Edit:

Input - Output

.. => cd ../../
... => cd ../../../

Thanks in advance!



Solution 1:[1]

If you don't mind having n-1 aliases defined after pressing . n times, add this to your .bashrc:

function update_dots() {
    READLINE_LINE=${READLINE_LINE}.
    if [[ "$READLINE_LINE" =~ ^\.(\.+)$ ]]; then
        DOT_CMD="cd ${READLINE_LINE//\./\.\.\/}"
        alias $READLINE_LINE="$DOT_CMD"
    fi
    READLINE_POINT=$(($READLINE_POINT+1))
}

bind -x '".":"update_dots"'

It works like this:

[thomas@corellia e]$ pwd
/tmp/a/b/c/d/e
[thomas@corellia e]$ .....
[thomas@corellia tmp]$ pwd
/tmp
[thomas@corellia tmp]$ alias
alias ..='cd ../../'
alias ...='cd ../../../'
alias ....='cd ../../../../'
alias .....='cd ../../../../../'

Solution 2:[2]

I'd just take the safe but boring route and define an alias for each level of dots up to some practical maximum:

dots=""
for((i=0; i<10; i++))
do
    dots+="."
    alias "$dots=b $dots"
done

It's not interesting, but it doesn't have any odd side effects either.

Solution 3:[3]

dots=".."
target="cd .."
for((i=0; i<10; i++))
do
    alias "$dots=$target"
    dots+="."
    target+="/.."
done
unset dots target

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tommi
Solution 2 that other guy
Solution 3 Jethro Yu