Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say I open ~/vim.txt, push that to background, then cd to another path. When I bring that job to foreground, is there an option to switch back to old path? I noticed it says pwd, so I assume it is possible.

share|improve this question

migrated from stackoverflow.com May 4 '11 at 20:49

This question came from our site for professional and enthusiast programmers.

Are you opening the file in vim? If so, a tag for vim to your question. – shellter May 2 '11 at 15:25
up vote 5 down vote accepted

This is possible in zsh, and in fact it's easy thanks to the direct access to the job parameters provided by the zsh/parameter module. You can use a job number or any job specification (%+, %-, %foo, etc.) as a subscript in the array.

zmodload zsh/parameter
fgcd () {
  local dir=$jobdirs[${1:-%+}]
  # If the jobspec matched, then call cd. Otherwise it's probably a bad
  # job spec, but call fg anyway to get the usual error message.
  if [[ -n $dir ]]; then cd $dir; fi
  fg $1

Bash also keeps track of the information, but I don't think it's exposed. On some systems, you can obtain the current working directory of the job's process, and switch to it. For example, on Linux, /proc/$pid/cwd is a symbolic link to that process's working directory.

fgcd () { # Linux only
  local pid=$(jobs -p $1)
  if [[ -n $pid ]]; then cd /proc/$pid/cwd; fi
  fg $1

Since it can also be useful, here's a zsh version. Unlike the function above, which switches to the job's original directory, this one switches to the current working directory of the job's process leader.

fgcd () { # Linux only
  local pid=${${${jobstates[${1:-%+}]}#*:*:}%\=*}
  if [[ -n $pid ]]; then cd /proc/$pid/cwd; fi
  fg $1
share|improve this answer
This is exactly what I was looking for, thanks! – Senthil May 3 '11 at 5:51
This works great, but unfortunately when I accidentally switch to non-existent job it switches from current dir to ~/. Any suggestions? I'm using the first answer btw. – sent-hil May 4 '11 at 23:45
@Senthil: In that case the job data was empty so cd was called with no argument (which means cd to your home directory). I've added a test in my answer. Tip: after calling cd, you can call cd - to go back to the directory you just left. – Gilles May 5 '11 at 0:14
That did the trick, thanks Gilles! (Thanks for cd - too). – sent-hil May 5 '11 at 1:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.