I’ve been playing around with bash scripting quite a bit recently in relation to my current job.
Came up with one that’s really useful (imho) around chkconfig
:
# mass set all services known to chkconfig to be `on` or `off` at given level
# written by warren myers - warren@warrenmyers.com
# 28 sep 2009
echo "USAGE:"
echo " $0 <level>Â [on|off]"
echo
# list all services, just the name, skip blank lines, do in order
SERVICES=`chkconfig --list | cut -f 1 | grep -v ^$ | grep -v ':' | sort`
for SERVICE in $SERVICES
do
  chkconfig --level $1 $SERVICE $2
  echo "$SERVICE has been altered for $1 to state $2"
done
Yes – there’s an evil you could perform:
for CS in `chkconfig --list | cut -f 1 | grep -v ^$ | grep -v ':'`
do
  chkconfig --level 12345 $CS off
done
So, if you wanted to stop all services from coming on at startup, you could – and not know you did it until you rebooted.
Warren,
just a style/good-practice recommendation:
Instead of:
SERVICES=`chkconfig –list | cut -f 1 | grep -v ^$ | grep -v ‘:’ | sort`
Use:
SERVICES=$(chkconfig –list | cut -f 1 | grep -v ^$ | grep -v ‘:’ | sort)
It’s easier to read than the ticks. 😉
Also, you might want to turn the usage message into a function. I do that all the time:
———- cut here ———–
usage() {
echo “usage: ${0##*/} [on|off]” >&2
exit 1
}
# and then, some parameter checking
[[ -z “$1” || -z “$2” ]] && usage
[[ “$2” == “on” || “$2” == “off” ]] || usage
———- cut here ———–
Thanks, @Alexei – I do typically do a usage of some kind, and of course checking your input is *always* a good idea =D
Curious, though – why is the $() preferable to “ for grabbing the output of an exec’d command into the variable?
Legibility. I work with UNIX for about 15 yrs now, shell-scripting probably the same. I *know* the ticks well enough. But every now and then, I still get caught in a messy sequence of ‘ and ” and `, mostly when they’re nested.
Thus, replacing the backtick with $( ) makes things one degree less messy.
IMHO, naturally 😉
Fair enough – rarely if ever see the $() construct in the environments I’ve been exposed-to: but good to know about 🙂