Domanda

I want create alias for open the last directory in the current directory, maybe I think it's possible to use this command for get name of directory : ls -1t | head -1 But I don't say to use it.

solved with function or with alias : alias oo='cd $(ls -1t | head -1)'

È stato utile?

Soluzione

First, don't create an alias! from man bash:

For almost every purpose, aliases are superseded by shell functions.

So unless you really know what the alias mechanism is, and you know you really need an alias, use a function instead.

The following function will get you to the last directory (with respect to sorting by name) of the current directory:

cdlast() {
    local shoptnullglob=$(shopt -p nullglob)
    shopt -s nullglob
    local dirs=( */ )
    $shoptnullglob
    ((${#dirs[@]})) && cd -- "${dirs[-1]}"
}

A few remarks: this will not take the hidden directories into account, unless have set the shell option dotglob. If there are not directories in the current directory, the function does nothing (but has a return code of 1).


If you need to cd into the last modified directory, things get trickier (and hence more interesting):

cdlast() {
    local shoptnullglob=$(shopt -p nullglob)
    shopt -s nullglob
    local dirs=( */ )
    $shoptnullglob
    ((${#dirs[@]})) || return 1
    local last=${dirs[0]}
    for d in "${dirs[@]}"; do
        [[ $d -nt $last ]] && last=$d
    done
    cd -- "$last"
}

If you like these functions, put them in you .bashrc.

Altri suggerimenti

The command you mentioned cannot differentiate between files and dirs, use the following instead:

LAST_DIR=$(ls -ltr | egrep ^d | awk '{ print $9 }'| head -1)
dirs=(*/)             # an array of directories in the CWD
last_dir=${dirs[-1]}  # the "last" directory lexicographically
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top