简体   繁体   中英

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!

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 ../../../../../'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM