Linux Sysadmin Test Prep

Basic Scripting

Basic Scripting

arguments

ArgumentMeaning
$0script file name
$1-9arguments
$#number of command line arguments passed
$@list of arguments passed
$?exit status of last process run
$$PID of script
$USERuser executing the script
$RANDOMrandom number
#!/bin/bash
# Usage: excludeFromBackup.sh <BACKUP_DIR> <EXCLUDE_FILETYPE>
BACKUP_DIR=$1
EXCLUDE_FILETYPE=$2
tar X <(for i in $BACKUP_DIR/*;
do file $i | grep -i $EXCLUDE_FILETYPE;
if [ $? -eq 0 ];
then echo $i;
fi;
done) -cJf backup.tar.xz $BACKUP_DIR/*

Conditions

if CONDITION; then
COMMANDS;
else
OTHER-COMMANDS
fi
File ConditionsTrue IF
-a fileexists
-d fileis a directory
-f fileis a regular file
-u fileSUID (set user ID) bit is set
-g fileSGID bit is set
-k filesticky bit is set
-r fileis readable
-s fileis not empty
-w fileis writable
-x fileis true if is executable
String ConditionsTrue IF
string1 = string2strings are equal
string1 != string2strings are not equal
STRING =~ REGEXstring equals regex
Integer ConditionsTrue IF
-eqequal
-nenot equal
-ltless than
-leless than or equal
-gtgreater than
-gegreater than or equal

For

for item in SEQUENCE; do
COMMANDS;
done
#!/bin/bash
for port in $(cat ports.txt); do
sudo netstat -lnp | grep -w $port
if [ $? -eq 0 ]; then
echo $port "is [ACTIVE]"
else
echo $port "is [INACTIVE]"
fi
done

While

while EVALUATION_COMMAND; do
EXECUTE_COMMANDS;
done
#!/bin/bash
# Usage: teaTasting.sh -n Name -t Tea -d Date
while getopts ":n:t:d:" arg; do
case $arg in
n) Name=$OPTARG;;
t) Tea=$OPTARG;;
d) Date=$OPTARG;;
esac
done
echo -e "\n$Name $Tea $Date\n"
Edit this page on GitHub