Improving repetitive tasks in function

stop_service ()
{
 sudo systemctl is-active --quiet video.service && sudo systemctl stop video.service && sudo rm /etc/systemd/system/video.service && echo stop video
 sudo systemctl is-active --quiet audio.service && sudo systemctl stop audio.service && sudo rm /etc/systemd/system/audio.service && echo stop audio
 sudo systemctl is-active --quiet stream.service && sudo systemctl stop stream.service && sudo rm /etc/systemd/system/stream.service && echo stop stream
 sudo systemctl is-active --quiet images.service && sudo systemctl stop images.service && sudo rm /etc/systemd/system/images.service && echo stop images
 sudo systemctl is-active --quiet browser.service && sudo systemctl stop browser.service && sudo rm /etc/systemd/system/browser.service && echo stop browser
 sudo systemctl is-active --quiet youtube.service && sudo systemctl stop youtube.service && sudo rm /etc/systemd/system/youtube.service && echo stop youtube

}

I am using this function to check if any one of these 6 services is running. I stop it, remove it and echo which service was stopped. Looking at this function though, I feel like there's a better way of doing this instead of repeating the same line 6 times. But my shell knowledge is limited so hopefully someone more experienced than me can assist.

Thanks

I don't know that this "improves" anything, but maybe it makes it more obvious that the same operations are performed for each service:

stop_service ()
{	for service in video audio stream images browser youtube
	do	sudo systemctl is-active --quiet "$service".service &&
		    sudo systemctl stop "$service".service &&
		    sudo rm /etc/systemd/system/"$service".service &&
		    echo "stop $service"
	done
}
1 Like

thanks for your reply, I'll give it a try.

A slight modification to Don Cragun's fine proposal would make the function more versatile / helpful, stopping one to many services:

stop_service () { for service
                   do   sudo systemctl is-active --quiet "$service".service &&
                        sudo systemctl stop "$service".service &&
                        sudo rm /etc/systemd/system/"$service".service &&
                        echo "stop $service"
                   done
                }
stop_service  video audio stream images browser youtube
stop_service  video
2 Likes

thanks for both suggestions. works great!