This makes issuing CTRL+Z immediately resume the previous job, as long as you have more than 1 job suspended. The only way to exit the while loop is to close programs until at most 1 backgrounded program is left.
function fgstack() {
local n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
while [[ n_jobs -gt 1 ]]; do
fg %-;
n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
done
}
If you want to give yourself a chance to break out from the two-job loop, suspending a job before before 0.2 seconds has passed does it CTRL+Z+Z: (zsh -- for bash you would need to use something else for getting the time):
function fgstack() {
local n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
while [[ n_jobs -gt 1 ]]; do
if [[ $SECONDS -lt 0.2 ]]; then
break
fi
typeset -F SECONDS=0
fg %-;
n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
done
}
Here's another, that requires fzf but gives you a menu if you have more than two options to choose from:
function fgstack() {
local n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
while [[ n_jobs -gt 1 ]]; do
if [[ n_jobs -eq 2 ]]; then
fg %-;
else
job=$(jobs | fzf -0 -1 | tr -cd "[:digit:]") && fg %$job
fi
n_jobs=$(jobs | tr -cd "[:digit:][:space:]" | wc -l)
done
Tested in zsh and bash -- bash seems to exit the while loop after returning from the first backgrounded job after invoking the function, edits & comments are welcome if someone knows how to fix that!
C-z C-z
backgrounds the foreground program, with a stop that's as brief as my ability to press two keys. – Gilles 'SO- stop being evil' Oct 25 '19 at 16:03C-z C-z
backgrounding one job and forgrounding the other, yes. I do wonder if any of the existing signals could be clobbered instead. There are a couple I don't care about, and even have disabled (C-s
for example). – Caleb Oct 25 '19 at 16:21C-s
is a terminal action that doesn't send a signal. The only signals areC-c
→ SIGINT,C-z
→ SIGTSTP andC-\
→ SIGQUIT. If you're happy withC-z C-z
, I suggest that you adapt my function to select whichever foreground job you want. – Gilles 'SO- stop being evil' Oct 25 '19 at 16:27