How Can I Run a Foreground Command from a Background Script?

0
26
Asked By CuriousCoder42 On

I'm working on a screensaver script that launches cBonsai after a certain period of inactivity. The script itself is functioning well, but it runs in the foreground, which prevents me from executing any other commands until it stops. When I try to run it in the background, cBonsai also ends up running in the background. I'm looking for a way to start a command in the foreground from a background process. I've considered job control, but it seems I'm only getting the PID of my script, not the command that's executed within it.

6 Answers

Answered By TechGuru99 On

It sounds like you're trying to have a process take over the terminal when it goes idle and then hand it back when you start typing. Is that right? You might need to consider how to manage the control of your terminal here.

Answered By NoobCoder On

This is a bit tricky. If you have a script (like a.sh) that runs a command (mycmd) and want to keep a.sh in the foreground but run mycmd in the background, you can simply edit a.sh to add an '&' at the end of the line where mycmd is called. If you want to manage mycmd's input/output after it's in the background, check out the 'coproc' feature in bash!

Answered By BashWhiz On

You can't completely do that, unfortunately. A PID needs to be associated with a TTY to be the controlling terminal. If another shell is already using that terminal, it won't properly show up under job control. Typically, for a command to be in the foreground of a shell, that shell needs to start the command.

Answered By CommandMaster On

Here's a tip: you can run your command as normal, then press Ctrl+Z to pause it, and then type 'bg' to send it to the background. You can bring it back to the foreground with 'fg %1' (replace 1 with your job number). If you add '&' at the end of your command, it runs in the background right away. Consider using tmux for a more robust solution, too!

Answered By WindowSwitcher On

Check out tmux for an easy way to handle this. You can create a new session in tmux and run your command there. Here’s a simple script:
```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 switch between windows easily!

Answered By ScriptSavvy On

You could turn your script into a service if you want something that runs independently without needing a terminal. This might give you the flexibility you're looking for!

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.