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! Here's an updated version of the script that meets your requirements:
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 PIDs pgrep -x $1 > /dev/null 2>&1 # 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." exit 1 fiThis version of the script hides the PIDs by redirecting the standard error (
2>&1) to/dev/null. If the program is not running, the script exits with a non-zero status code (exit 1).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.