How to run a command in the background and then kill it under bash terminal?

If you've ever worked with long-running scripts or applications that don't return control to the shell prompt, you know how frustrating it is to wait. But what if there was a way to continue using your terminal while these processes are running in the background?
Today we're going to explore how to run commands in the background and then kill them using the bash. Let's dive right in!

Running commands in the background

By appending & to the end of your command, you can run any command in the background in bash. Here's a quick example using Ruby on Rails. If you start your Rails server with the rails s command, you can run it in the background with

rails s &

Once your background job is running, control is returned to your terminal. You can verify that your job is running by using the jobs command.

Killing background commands

Your code runs smoothly in the background, but how do you stop it when you're done? Killing background processes in the bash is easy, thanks to the kill command.

kill -9 %

When you use the percent symbol %, you're referring to the most recently placed background process. The -9 signal with a kill command is SIGKILL, which forces the process to stop immediately.

Conclusion

Running and killing background commands in the bash can make your development workflow much smoother. It's a handy technique to have in your developer's toolkit.