Search code examples
unixterminallscd

Change to xth directory terminal


Is there a way in a unix shell (specifically Ubuntu) to change directory into the xth directory that was printed from the ls command? I know you can sort a directory in multiple ways, but using the output from ls to get the xth directory?

An example shell:

$ ls
$ first_dir second_dir third_really_long_and_complex_dir

where I want to move into the third_really_long_and_complex_dir by passing 3 (or 2 in proper array format). I know I could simply copy and paste, but if I'm already using the keyboard, it would be easier to type something like "cdls 2" or something like that if I knew the index.


Solution

  • The main problem with cd in an interactive session is that you generally want to change the current directory of the shell that is processing the command prompt. That means that launching a sub-shell (e.g. a script) would not help, since any cd calls would not affect the parent shell.

    Depending on which shell you are using, however, you might be able to define a function to do this. For example in bash:

    function cdls() {
        # Save the current state of the nullglob option
        SHOPT=`shopt -p nullglob`
    
        # Make sure that */ expands to nothing when no directories are present
        shopt -s nullglob
    
        # Get a list of directories
        DIRS=(*/)
    
        # Restore the nullblob option state
        $SHOPT
    
        # cd using a zero-based index
        cd "${DIRS[$1]}"
    }
    

    Note that in this example I absolutely refuse to parse the output of ls, for a number of reasons. Instead I let the shell itself retrieve a list of directories (or links to directories)...

    That said, I suspect that using this function (or anything to this effect) is a very good way to set yourself up for an enormous mess - like using rm after changing to the wrong directory. File-name auto-completion is dangerous enough already, without forcing yourself to count...