I'm working on a script to create a 'screensaver' that launches cBonsai after a certain period of inactivity. It's doing fine if I run it in the foreground, but I can't use my terminal for other commands when that happens. I've tried running it in the background, but now cBonsai is also running in the background. How do I execute a command in the foreground from a background script? I've looked into job control, but I only get the PID of the script, not the executed command.
5 Answers
This can get a bit tricky! If you're running a script that calls another command, like 'mycmd', just add an ampersand (&) at the end of that line in your script. That way, 'mycmd' will run in the background while 'a.sh' runs in the foreground. You should also look into the coproc feature in bash if you need to handle input/output for 'mycmd' after launching it.
Have you tried using tmux? It's super helpful for this kind of task. You can set it up to run cBonsai in a new window, allowing you to switch back and forth. Here's a snippet to get you started:
```bash
#!/usr/bin/env bash
[[ -n $TMUX ]] || exec tmux new-session "$0" "$@"
tmux new-window -n screensaver cbonsai -liWC
for i in $(seq 1 10); do
tmux previous-window
printf 'Round %2dn' "$i"
sleep 2
tmux next-window
sleep 2
done
tmux kill-window -t screensaver
```
This way, you can have a running session and easily navigate between tasks.
Honestly, you can't completely do that since a background process started from another terminal might not follow the normal job control. It needs to be initiated from the controlling terminal to properly show up in the foreground. You could, however, explore making it a service to manage the behavior.
It sounds like you want a way to take over your terminal when it's idle. You might need to dig into how job control works so that when your script runs, it can take over the terminal as needed and return control when you're ready to type again.
You could try running your script normally, pausing it with Ctrl+Z, and then using the 'bg' command to push it to the background. You can bring it back to the foreground with 'fg %1' (replace 1 with your job number). If you want it to start in the background automatically, just put an '&' at the end of your command. If you’re working in a tmux session, it’ll make things a lot easier!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically