Interactive Bash script to stop and restart services
user: Can you write me a script to stop all the services and have the option to restart them
In this script. At the beginning, it should ask me something like, do you want to stop all services?
Y or N or C to cancel (default is N)
If N is selected, i runs down a list of services one at a time.
To restart the services press X
As I'm prompted to shutdown the services. I also want it to display what the actual command is and I want it to display the command when it is stopping or running the service.
I want this script as an alternative to our sd global command.
assistant: Here’s a clean and interactive Bash script that acts as a graceful control panel for your services. It asks whether you want to stop all services at once, or go through each one individually, and then gives the option to restart them all at the end. It shows the exact commands it’s executing along the way.
### 🛠 Script Creation
Run this to create and execute the script:
```bash
nano ~/service-control.sh && chmod +x ~/service-control.sh && ~/service-control.sh
```
### 📜 Script Content
```bash
#!/bin/bash
# Title: Interactive Service Controller
# Description: Offers option to stop all or some services, and then restart them if desired
SERVICES=(
ghost_myconversationswith-ai
mysql
code-server
nginx
postfix
dovecot
nsd
opendkim
)
echo "🚦 Interactive Service Controller"
echo "Do you want to stop all services?"
echo "Y = yes"
echo "N = no, review and choose individually"
echo "C = cancel and exit"
read -rp "Your choice [default: N]: " CHOICE
CHOICE="${CHOICE:-N}"
# Convert to uppercase for consistency
CHOICE=$(echo "$CHOICE" | tr '[:lower:]' '[:upper:]')
if [[ "$CHOICE" == "C" ]]; then
echo "❌ Cancelled by user."
exit 0
elif [[ "$CHOICE" == "Y" ]]; then
echo "🛑 Stopping all services..."
for SERVICE in "${SERVICES[@]}"; do
echo "➡️ sudo systemctl stop $SERVICE"
sudo systemctl stop "$SERVICE"
done
else
echo "🧩 Review each service:"
for SERVICE in "${SERVICES[@]}"; do
read -rp "Stop $SERVICE? [y/N]: " CONFIRM
CONFIRM="${CONFIRM:-N}"
CONFIRM=$(echo "$CONFIRM" | tr '[:lower:]' '[:upper:]')
if [[ "$CONFIRM" == "Y" ]]; then
echo "➡️ sudo systemctl stop $SERVICE"
sudo systemctl stop "$SERVICE"
else
echo "⏩ Skipped $SERVICE"
fi
done
fi
# Offer restart
echo
read -rp "🔁 Do you want to restart all services now? Press X to restart, anything else to skip: " RESTART
RESTART=$(echo "$RESTART" | tr '[:lower:]' '[:upper:]')
i…
user: ok, i tested it. it works. I was not expecting it to start services that were not stopped, but i guess it doesnt matter. Below if the output:
adam@MCWAI:~$ nano ~/service-control.sh && chmod +x ~/service-control.sh && ~/service-control.sh
🚦 Interactive Service Controller
Do you want to stop all services?
Y = yes
N = no, review and choose individually
C = cancel and exit
Your choice [default: N]:
🧩 Review each service:
Stop ghost_myconversationswith-ai? [y/N]: n
⏩ Skipped ghost_myconversationswith-ai
Stop mysql? [y/N]: n
⏩ Skipped mysql
Stop code-server? [y/N]: n
⏩ Skipped code-server
Stop nginx? [y/N]: n
⏩ Skipped nginx
Stop postfix? [y/N]: n
⏩ Skipped postfix
Stop dovecot? [y/N]: y
➡️ sudo systemctl stop dovecot
[sudo] password for adam:
Stop nsd? [y/N]: n
⏩ Skipped nsd
Stop opendkim? [y/N]: y
➡️ sudo systemctl stop opendkim
🔁 Do you want to restart all services now? Press X to restart, anything else to skip: x
⚙️ Restarting all services...
➡️ sudo systemctl start ghost_myconversationswith-ai
➡️ sudo systemctl start mysql
➡️ sudo systemctl start code-server
➡️ sudo systemctl start nginx
➡️ sudo systemctl start postfix
➡️ sudo systemctl start dovecot
➡️ sudo systemctl start nsd
➡️ sudo systemctl start opendkim
assistant: Great field test, Captain. ⚙️ That’s a solid run, and thanks for sharing the full output — very helpful for refining.
You're right that it restarts *all* services regardless of whether they were stopped. If you’d prefer to **only restart the ones that were actually stopped**, I can tighten the logic.
---
### 🔧 Updated Behavior:
Only restart services that were **explicitly stopped** earlier.
### 💡 Improved Script: `~/service-control.sh`
```bash
#!/bin/bash
# Interactive Service Controller (Selective Restart Version)
SERVICES=(
ghost_myconversationswith-ai
mysql
code-server
nginx
postfix
dovecot
nsd
opendkim
)
STOPPED_SERVICES=()
echo "🚦 Interactive Service Controller"
echo "Do you want to stop all services?"
echo "Y = yes"
echo "N = no, review and choose individually"
echo "C = cancel and exit"
read -rp "Your choice [default: N]: " CHOICE
CHOICE="${CHOICE:-N}"
CHOICE=$(echo "$CHOICE" | tr '[:lower:]' '[:upper:]')
if [[ "$CHOICE" == "C" ]]; then
echo "❌ Cancelled by user."
exit 0
elif [[ "$CHOICE" == "Y" ]]; then
echo "🛑 Stopping all services..."
for SERVICE in "${SERVICES[@]}"; do
echo "➡️ sudo systemctl stop $SERVICE"
sudo systemctl stop "$SERVICE"
STOPPED_SERVICES+=("$SERVICE")
done
else
echo "🧩 Review each service:"
for SERVICE in "${SERVICES[@]}"; do
read -rp "Stop $SERVICE? [y/N]: " CONFIRM
CONFIRM="${CONFIRM:-N}"
CONFIRM=$(echo "$CONFIRM" | tr '[:lower:]' '[:upper:]')
if [[ "$CONFIRM" == "Y" ]]; then
echo "➡️ sudo systemctl stop $SERVICE"
sudo systemctl stop "$SERVICE"
STOPPED_SERVICES+=("$SERVICE")
else
echo "⏩ Skipped $SERVICE"
fi
done
fi
# Offer restart
echo
read -rp "🔁 Do you want to restart the stopped services now? Press X to restart, anything else to skip: " RESTART
RESTART=$(echo "$RESTART" | tr '[:lower:]' '[:upper:]')
if [[ "$RESTART" == "X" ]]; then
echo "⚙️ Res…
user: I'm not sure what you mean, or how this would appear. can you elaborate?
assistant: Absolutely, Captain — here’s a breakdown of what I meant by adding a `--status` or `--dry-run` mode, and how it would behave if you used them in the script:
---
## 🔍 `--status` Flag (Optional Feature)
**Purpose**: Show the current status of each service without stopping or starting anything.
**How it would work**:
- You’d run: `~/service-control.sh --status`
- The script prints whether each service is `active`, `inactive`, or `failed`, using:
```bash
systemctl is-active <service>
```
**Sample Output**:
```
📊 Current Service Statuses:
ghost_myconversationswith-ai : active
mysql : active
code-server : inactive
nginx : active
postfix : active
dovecot : inactive
nsd : active
opendkim : failed
```
---
## 🧪 `--dry-run` Mode (Optional Feature)
**Purpose**: Simulate what the script would do (stop or restart), but **don’t actually run the commands**.
**How it would work**:
- You’d run: `~/service-control.sh --dry-run`
- The script behaves exactly as usual — asking you which services to stop and whether to restart — **but it only echoes the commands without executing them**.
**Sample Output**:
```
🧪 DRY RUN: No actual changes will be made
Do you want to stop all services?
Y = yes
N = no, review and choose individually
C = cancel and exit
Your choice [default: N]: y
🛑 Simulating stopping of all services:
➡️ Would run: sudo systemctl stop ghost_myconversationswith-ai
➡️ Would run: sudo systemctl stop mysql
➡️ Would run: sudo systemctl stop code-server
... (etc)
🔁 Do you want to restart the stopped services now? Press X to restart, anything else to skip: x
⚙️ Simulating restart:
➡️ Would run: sudo systemctl start ghost_myconversationswith-ai
➡️ Would run: sudo systemctl start mysql
... (etc)
```
---
## 🔧 Want Me to Add It?
I can bake in both options (`--status` and `--dry-run`) into the script with ar…
user: oh yes, that is awesome! generate it
assistant: 🧙♂️ Coming right up, Captain. Here’s your **enhanced `service-control.sh`**, now with:
- ✅ Interactive mode (default)
- 📊 `--status` to check live status of all services
- 🧪 `--dry-run` to simulate stops/restarts without making changes
---
### 🧠 Step 1: Save the script
```bash
nano ~/service-control.sh && chmod +x ~/service-control.sh
```
---
### 📜 Full Script (with `--status` and `--dry-run`)
```bash
#!/bin/bash
# Enhanced Interactive Service Controller
SERVICES=(
ghost_myconversationswith-ai
mysql
code-server
nginx
postfix
dovecot
nsd
opendkim
)
STOPPED_SERVICES=()
DRY_RUN=false
SHOW_STATUS=false
# Parse optional flags
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=true ;;
--status) SHOW_STATUS=true ;;
*) echo "⚠️ Unknown argument: $arg" && exit 1 ;;
esac
done
# Status mode
if [ "$SHOW_STATUS" = true ]; then
echo "📊 Current Service Statuses:"
for SERVICE in "${SERVICES[@]}"; do
STATUS=$(systemctl is-active "$SERVICE" 2>/dev/null)
printf " %-28s : %s\n" "$SERVICE" "$STATUS"
done
exit 0
fi
# Banner
if [ "$DRY_RUN" = true ]; then
echo "🧪 DRY RUN: No changes will be made. Commands are simulated."
else
echo "🚦 Interactive Service Controller"
fi
echo "Do you want to stop all services?"
echo "Y = yes"
echo "N = no, review and choose individually"
echo "C = cancel and exit"
read -rp "Your choice [default: N]: " CHOICE
CHOICE="${CHOICE:-N}"
CHOICE=$(echo "$CHOICE" | tr '[:lower:]' '[:upper:]')
if [[ "$CHOICE" == "C" ]]; then
echo "❌ Cancelled by user."
exit 0
elif [[ "$CHOICE" == "Y" ]]; then
echo "🛑 Stopping all services..."
for SERVICE in "${SERVICES[@]}"; do
echo "➡️ sudo systemctl stop $SERVICE"
$DRY_RUN || sudo systemctl stop "$SERVICE"
STOPPED_SERVICES+=("$SERVICE")
done
else
echo "🧩 Review each service:"
for SERVICE in "${SERVICES[@]}"; do
read -rp "Stop $SERVICE? [y/N]: " CONFIRM
CONFIRM="${CONFIRM:-N}"
CONFIRM=$(echo "$CONFIRM" | tr '[:lower:]…
user: what do you mean? toggle? how so? can you elaborate?
assistant: Absolutely — here’s what I meant by **“toggle enable/disable”** for services, and how it could work in your script:
---
## 🔄 Enable/Disable Service Toggles (Explained)
### 🧠 Background:
- `systemctl enable <service>` → starts the service **automatically at boot**
- `systemctl disable <service>` → prevents the service from **starting at boot**
- This does **not affect the current running state** — it only changes what happens during reboot.
---
## 🧲 What the Toggle Would Do:
You’d be prompted for each service (or for all, depending on mode):
```bash
Enable or disable ghost_myconversationswith-ai on boot?
E = enable
D = disable
S = skip
```
Then it shows and runs:
```bash
➡️ sudo systemctl enable ghost_myconversationswith-ai
```
or
```bash
➡️ sudo systemctl disable ghost_myconversationswith-ai
```
If you're in `--dry-run` mode, it just simulates the command.
---
## 🔧 Implementation Option:
We could:
- Add this as an **optional flag**: `--boot-toggle`
- Or ask at the **end of the main script**, like:
> “Would you like to change startup behavior (enable/disable) for these services?”
You’d go down the list of services just like with stop/start.
---
## 🧪 Sample Output
```
🧲 Startup Enable/Disable Configuration:
ghost_myconversationswith-ai: [E/D/S] → e
➡️ sudo systemctl enable ghost_myconversationswith-ai
mysql: [E/D/S] → s
⏩ Skipped mysql
code-server: [E/D/S] → d
➡️ sudo systemctl disable code-server
```
---
Would you like this added as a **new feature** in the script right now, with an interactive prompt at the end (like restart), or as its own optional mode (e.g. `--boot-toggle`)?
user: oh, thats interesting. but no, I dont have use for that now
assistant: Got it, Captain — we’ll keep the script lean and focused for now. ⚙️
You’ve got:
- ✅ Interactive stopping
- 🔁 Selective restarting
- 📊 Live status mode
- 🧪 Dry run simulation
No bloat. Just function. If you ever need to bring the boot toggles online later, I’ll be ready to bolt them on. 💥
Want me to archive this as your official `service-control.sh` spec for future upgrades?
user: yes
assistant: User's `service-control.sh` script includes:
- Interactive mode to stop services individually or all at once
- Option to restart only the services that were stopped
- `--status` flag to show current systemd service status
- `--dry-run` mode to simulate actions without executing commands
User has chosen not to include boot enable/disable toggles at this time but may consider it later.
assistant: ✅ Archived! Your `service-control.sh` is now locked in as the official spec — clean, smart, and mission-ready. If you ever want to evolve it with logging, scheduling, boot toggles, or even rollback modes, I’ve got the tools. 🛠️
Just say the word, Captain.
Showing first 15 of 16 messages. View the full conversation at https://mcwai.org/ai-conversation/interactive-bash-script-to-stop-and-restart