Taylor Reed
Taylor Reed

Reputation: 355

run command in bash and then exit without killing the command

I am attempting to run a couple commands in a bash script however it will hang up on my command waiting for it to complete (which it wont). this script is simply making sure its running.

#!/bin/bash
ps cax | grep python > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running... Starting..."
  python likebot.py
  echo $(ps aux | grep python | grep -v color | awk {'print $2'})
fi

Once it gets to the python command it hangs up while the command is being executed. its not till i cntrl c before it gives the pid. is there anyway i can have it run this bash script and exit the bash script once the commands were run (without waiting for them to complete).

Upvotes: 2

Views: 4041

Answers (2)

tolanj
tolanj

Reputation: 3724

Since it looks like likebot should be always running you might want to consider 'nohup' as well, with a bare & the job is still a child of your login process and will die if that dies.

Upvotes: 2

William Pursell
William Pursell

Reputation: 212198

In general, if you want to execute a command and not wait for it, you can simply use & as the delimiter rather than ; or a newline. When doing so, the pid of that process is available to the shell in the special variable !. If you want to wait for that process to complete, you can use wait. If you do not wish to wait for it, then simply omit the wait. In your case:

python likebot.py &  # Start command asynchronously
echo $!              # echo the pid of the most recent asynchronous process

Upvotes: 9

Related Questions