linux shell syntaxesHere in the examples, I published commonly used linux shell syntaxes that are commonly looked up.- Simple variable assignment and referring it later:
LINPACK_NAME=l_lpk_p_11.1.2.005.tgz
echo $LINPACK_NAME MISC_SCRIPTS=(
poll.curr.freq.sh \
reconfig.multi.eth.py \
init.satool.sh \
)- IF and FOR loop example, also test if file exists:
for i in "${PASSWORD_LOCS[@]}"
do
echo looking for password file in $i
if [ -s $i/passwd.log ]
then
echo found the password file in $i.
PASSWORD_FILE=$i/passwd.log
break
fi
done- For loop over array structures, as well as checking if directory exists:
for i in "${DIRECTORIES[@]}"
do
echo ---------------
if [ ! -d $i ]
then
mkdir $i
else
echo $i already exist.
fi
done- For loop over array structures and referencing another array elements using index:
for (( i=0; i < ${#MOUNT_SHARES[@]}; i++ ))
do
echo ---------------------------
echo setting user credentials for ${MOUNT_USERS_LABELS[$i]} ...
# if user/pw is not defined at this point.
if [ ${MOUNT_USERS[$i]} == 0 ] || [ ${MOUNT_PWS[$i]} == 0 ]
then
... fi
done - Check if variable is empty
if [ -z $PASSWORD_FILE ]
then
echo unable to locate password file.
else
echo password file: $PASSWORD_FILE
fiThe trick here is the if the variable is not empty, the above snippet will fail with syntax error, here is the better version, that works with both empty and non-empty cases by enclosing the variable within double-quote: if [ -z "$PASSWORD_FILE" ]
then
echo unable to locate password file.
else
echo password file: $PASSWORD_FILE
fi- Case structure as well as default case.
case "$RHEL_VERSION" in
"Red Hat Enterprise Linux Server release 6.7 (Santiago)")
echo "RHEL 6.7 is detected"
RHEL_ISO_PATH=$RHEL67_PATH_STRING
;;
"Red Hat Enterprise Linux Server release 6.8 (Santiago)")
echo "RHEL 6.8 is detected"
RHEL_ISO_PATH=$RHEL68_PATH_STRING
;;
"Red Hat Enterprise Linux Server release 7.2 (Maipo)")
echo "RHEL 7.2 is detected"
RHEL_ISO_PATH=$RHEL72_PATH_STRING
;;
*)
echo "Unknown linux version."
RHEL_ISO_PATH=$RHEL_VERSION_UNSUPPORTED
RHEL_VERSION=$RHEL_VERSION_UNSUPPORTED
esac
- Test if two strings are equal:
if [ "$RHEL_ISO_PATH" == $RHEL72_PATH_STRING ]
then
yum-config-manager --enable
else
echo no need for yum-config-manager --enable
fi
Source: linux shell syntaxes (//)