electriccello
electriccello

Reputation: 67

How to recursively exit nested shells?

I use the Ranger file manager in my terminal to move around. Every time I use the S command to drop into a new directory, Ranger is actually launching a new shell. When I want to close a terminal window I need to run exit as many times as I have changed directories with Ranger. Is there a command that will run exit recursively for me until the window closes? Or better yet is there a different Ranger command to use?

Upvotes: 3

Views: 830

Answers (2)

Simba
Simba

Reputation: 27588

Don't enter a sub-shell, just quit ranger and let the shell sync the directory back from ranger.

function ranger {
    local IFS=$'\t\n'
    local tempfile="$(mktemp -t tmp.XXXXXX)"
    local ranger_cmd=(
        command
        ranger
        --cmd="map Q chain shell echo %d > "$tempfile"; quitall"
    )

    ${ranger_cmd[@]} "$@"
    if [[ -f "$tempfile" ]] && [[ "$(cat -- "$tempfile")" != "$PWD" ]]; then
        cd -- "$(cat "$tempfile")" || return
    fi
    command rm -f -- "$tempfile" 2>/dev/null
}

Press capital Q to quit ranger, after which the shell will sync directory automatically to the same one within ranger.

This is very flexible and you can use q to quit normally without syncing the dir back to the shell.

Update:

. ranger to open ranger is another solution, which is NOT recommended. Because compared with previous method, quitting from . ranger with q will always sync the dir back to the shell from ranger. You have no control on this behavior.

No real solution to this. It's oft requested but not as easy as people think. You can source ranger, so start it like this . ranger. That'll cd to ranger's cwd when quitting.

References

Upvotes: 4

electriccello
electriccello

Reputation: 67

@Simba thanks for the great answer and the link to the docs.

In the end, the easiest answer was to just create an alias in my .bashrc like the docs recommend

alias ranger=". ranger"

Now when I use Q to quit, it automatically switches to the new directory, and only requires running exit one time to close the window.

Upvotes: 1

Related Questions