Just deleted tons of stale, unsused user accounts. Here are some KSH shell basics and special shell variable. I need to Google them up myself to get reminded that ‘$?’ is the output variable for script execution. That is, it’s 0 for successful execution and 1 if there is any error.
Special shell variables
There are some variables which are set internally by the shell and which are available to the user:
Name Description
——————————————————————————–
$1 – $9 these variables are the positional parameters.
$0 the name of the command currently being executed.
$# the number of positional arguments given to this
invocation of the shell.
$? the exit status of the last command executed is
given as a decimal string. When a command
completes successfully, it returns the exit status
of 0 (zero), otherwise it returns a non-zero exit
status.
$$ the process number of this shell – useful for
including in filenames, to make them unique.
$! the process id of the last command run in
the background.
$- the current options supplied to this invocation
of the shell.
$* a string containing all the arguments to the
shell, starting at $1.
$@ same as above, except when quoted.
Branching
if then fi
if [[ $value -eq 7 ]];then
print "$value is 7"
fi
or:
if [[ $value -eq 7 ]]
or:
then
print "$value is 7"
fi
if [[ $value -eq 7 ]];then print "$value is 7";fi
if then else fi
if [[ $name = "John" ]];then
print "Your welcome, ${name}."
else
print "Good bye, ${name}!"
fi
if then elif then else fi
if [[ $name = "John" ]];then
print "Your welcome, ${name}."
elif [[ $name = "Hanna" ]];then
print "Hello, ${name}, who are you?"
else
print "Good bye, ${name}!"
fi
case esac
case $var in
john|fred) print $invitation;;
martin) print $declination;;
*) print "Wrong name...";;
esac
——————————————————————————–
Looping Command Syntax for Scripts
while do done
while [[ $count -gt 0 ]];do
print "\$count is $count"
(( count -= 1 ))
done
until do done
until [[ $answer = "yes" ]];do
print -n "Please enter \"yes\": "
read answer
print ""
done
for var in list do done
for foo in $(ls);do
if [[ -d $foo ]];then
print "$foo is a directory"
else
print "$foo is not a directory"
fi
done
continue…break
One can skip the rest of a loop and directly go to the next iteration with: “continue”.
while read line
do
if [[ $line = *.gz ]];then
continue
else
print $line
fi
done
One can also prematurely leave a loop with: “break”.
while read line;do
if [[ $line = *!(.c) ]];then
break
else
print $line
fi
done
http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html
Removing accounts from predefine list:
#!/bin/ksh
for each in `cat ./list-a`
do
grep -i $each /etc/passwd
if [[ $? -eq 1 ]]; then
echo "$each does not exists."
sleep 2
continue;
else
echo "$each exists"
echo "Deleting account.. "
sleep 2
userdel $each
echo "$each deleted"
sleep 5
fi
done
Or course, the sleep there is just for aesthetic.. I want to see the screen