How can I run a foreground command from a background script?

0
10
Asked By CuriousCoyote92 On

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

Answered By DevDude42 On

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.

Answered By CommandWizard58 On

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.

Answered By CodeCracker33 On

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.

Answered By TechyTurtle82 On

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.

Answered By ScriptSavvy99 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.