I did a script in bash, but it geets in some sort of a loop. My script is like a reverse operation with an systemctl service and it's running like this :
if systemctl status service | grep -q "Active: inactive"; then
read -r -p "Service is inactive do you want to start it? : [y/N] : " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
systemctl start `service` && echo "Service is active"
else
echo "Service stays inactive"
fi
fi
if systemctl status service | grep -q 'Active: active'; then
read -r -p "Service is active, do you want to stop it? [y/N] : " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
systemctl stop service && echo "Service is inactive"
else
echo "Service stays active"
fi
fi
The problem is when it reach the first part and I want to start it, it jumps to the second part when it asks me if I want to stop it, is there any way to prevent bash doing this and stop it?
Use an else
block:
toggle_service() {
local response service=$1
if systemctl is-active "$service"; then
read -r -p "Service is inactive do you want to start it? : [y/N] : " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
systemctl start "$service" && echo "Service is active" >&2
else
echo "Service stays inactive"
fi
else
read -r -p "Service is active, do you want to stop it? [y/N] : " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
systemctl stop "$service" && echo "Service is inactive" >&2
else
echo "Service stays active" >&2
fi
fi
}
...or, a DRYer version :
toggle_service() {
local action state_name response service=$1
if systemctl is-active "$service"; then
state_name=active; action=stop
else
state_name=inactive; action=start
fi
read -r -p "Service is ${state_name}, do you want to ${action} it?" response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
systemctl "$action" "$service" && echo "Action complete: ${action} ${service}" >&2
else
echo "${service} remains ${state_name}" >&2
fi
}
Either one can be invoked with:
toggle_service sshd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.