How to exit the Ranger file explorer back to command prompt but keep the current directory?

Solution 1:

According to its manual

--choosedir=targetfile    
    Allows you to pick a directory with ranger. When you exit ranger, it will write the last visited directory into targetfile.

So all you need to do is create an alias like this:

alias ranger='ranger --choosedir=$HOME/.rangerdir; LASTDIR=`cat $HOME/.rangerdir`; cd "$LASTDIR"'

And writing this alias into the rc of your favoured shell is recommended.

Solution 2:

Shift + S

If you hit Shift + S, it opens a new shell on the current directory.

Then if you hit Ctrl + D on the shell, it goes back to ranger.

This workaround is often good enough.

By the way, I've given up on file managers for a few years now, I just have this in my bashrc instead and I navigate directories simply with tab complete, it's good enough for me:

c() {
  if [ -n "$1" ]; then
    cd "$1" || return 1
  else
    cd ..
  fi
  ll
}
ll() ( ls -hl --time-style="+%Y-%m-%d_%H:%M:%S" "$@"; )

GitHub upstream.

Solution 3:

I found an easier solution. When you install ranger, it will put a script in your bin folder which, if executed, will start the program. But if you source it, with

$ source ranger

it will launch ranger and drop you in the last visited folder when you exit.

so if you want this behavior by default, just do

$ alias ranger='source ranger'

or even better put it into your .bashrc file.

To see the documentation and implementation for this feature, read the ranger script in your bin folder.

Solution 4:

To piggy back of of Gombai Sándor's answer, i suggest making a minor adjustment to the alias:

alias ranger='ranger --choosedir=$HOME/.rangerdir; LASTDIR=`cat $HOME/.rangerdir`; cd "$LASTDIR"'

By changing "$Home/rangerdir" to "$Home/.rangerdir" you make the file created by the alias hidden. just makes it so it is not annoyingly cluttering up the home folder. it makes no functional difference to how it works.