문제

My bash scripting skills are very rusty (it's been ~10 years since I scripted regularly). So, I'm probably overlooking something obvious. I am trying to get the following script to work:

#!/bin/bash

SSID=$(iwgetid -r)

if [[ $SSID = NETWORK ]]; then

if (( $(ps aux | grep [s]shd | wc -l) > 0 )); then
sudo service ssh stop

if (( $(ps aux | grep [s]mdb | wc -l) > 0 )); then
sudo service smbd stop

if (( $(ps aux | grep [n]mdb | wc -l) > 0 )); then
sudo service nmbd stop

else
echo You are not connected to NETWORK
fi
fi
fi
fi
exit 0

What it should do: If I am connected to particular network (SSID removed from script), check to see if ssh, smbd, and nmbd are running, and if so, stop them. If they aren't, do nothing. If not connected to the network, say so and exit. Bash seems to be ignoring the last 2 if...then statements, and I'm not sure why (Wrong order maybe? Conditional formatting incorrect?)

Any help would be appreciated. Also, if you have style tips, I'll take those too (like I said, I'm very rusty). I spent a few hours looking around here and Google, but couldn't find anything relevant and helpful.

도움이 되었습니까?

해결책

You almost certainly meant to do this:

SSID=$(iwgetid -r)

if [[ $SSID = NETWORK ]]; then

  if (( $(ps aux | grep [s]shd | wc -l) > 0 )); then
    sudo service ssh stop
  fi

  if (( $(ps aux | grep [s]mdb | wc -l) > 0 )); then
    sudo service smbd stop
  fi

  if (( $(ps aux | grep [n]mdb | wc -l) > 0 )); then
    sudo service nmbd stop
  fi
else
  echo You are not connected to NETWORK
fi

But there is no real cost to running service stop on something which is not running, so you can simplify:

SSID=$(iwgetid -r)
if [[ $SSID = NETWORK ]]; then
  sudo service ssh stop
  sudo service smbd stop
  sudo service nmbd stop
else
  echo You are not connected to NETWORK
fi

Finally, I would recommend not using sudo inside the script. Instead, run the script itself with sudo check_ssid (or whatever it is called), so that the script ends up being:

SSID=$(iwgetid -r)
if [[ $SSID = NETWORK ]]; then
  service ssh stop
  service smbd stop
  service nmbd stop
else
  echo You are not connected to NETWORK
fi

By the way, if you really want to use ps and grep to check if a process is running, consider my answer here: How to test if a process is running with grep in bash?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top