Make a bash script that takes a program name as an argument and checks if there's a…
- User
Make a bash script that takes a program name as an argument and checks if there's a running process for it using pgrep
- Assistant
Here's a simple bash script that takes a program name as an argument and checks if there's a running process for it using
pgrep:bash#!/bin/bash # Check if an argument was provided if [ -z "$1" ]; then echo "Usage: $0 <program_name>" exit 1 fi # Use pgrep to check for the process pgrep -x $1 > /dev/null # Check the exit status of pgrep and print the result if [ $? -eq 0 ]; then echo "Process $1 is running." else echo "Process $1 is not running." fiTo use this script, save it to a file (e.g.,
check_process.sh), make it executable withchmod +x check_process.sh, and then run it with the name of the program you want to check as an argument:bash./check_process.sh myprogramThe script will check if there's a running process for
myprogramand print the result. Note that the-xoption inpgreprequires an exact match of the program name. - User
Thanks, can you also not show the process IDs if the program is running? And if the program is not running, exit with a non-zero status code
- Assistant
Sure, I can modify the script to meet your requirements. Here's the updated version:
bash#!/bin/bash # Check if an argument was provided if [ -z "$1" ]; then echo "Usage: $0 <program_name>" exit 1 fi # Use pgrep to check for the process without showing the process IDs pgrep -qx $1 # Check the exit status of pgrep and print the result if [ $? -eq 0 ]; then echo "Process $1 is running." exit 0 else echo "Process $1 is not running." exit 1 fiIn this updated script, the
-qoption is added topgrepto suppress the output of process IDs. If the program is running, the script will print "Process 1 is not running." and exit with a status code of 1.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.