Linux shell scripting basics

  • Strings
    • == equal; != Not equal, -z Null/empty/zero length; -n NOT empty/null
  • Number:
    • eq Equal; -ne Not equal; -gt Greater than; -lt Less than;
    • -ge Greater than or Equal to; -le Less than or Equal to
  • Files:
    • -e file exist; -f is a file; -d is a directory; -s file exists and non-zero length;
    • -g have guid, -u have suid, -r readable; -w writable; -x executable)
  • Man pages:
    • man test

1. Strings:

cat > <<EOF
user=$(whoami)             (Assign shell command output to a variable)
echo “Hello! ” $user
chmod +x         (Grant execute permission)
./                          (Run script)

read -p “Enter a string [e.g abc.123]: ” str
if  [  !  -z  $str  ]  &&  [  -n  $str  ]; then
echo “String is NOT empty and its length is: ${#str}”
echo “First three chars are: ${str:0:3}”
echo “All chars after . are ${str#*.}”
echo “ERROR: String is empty” >&2     (Redirects as stderr on console)

c) #Check  status of a service and take action accordingly
systemctl is-active httpd  &> /dev/null                (Sends stdout and stderr to /dev/null)
if [ $? -eq 0 ]; then                      (If status code=0, means Success)
   echo “Service is started”
elif [ $? -ne 0 ]; then               (If status code>0, means Unsuccessful
  echo “Service is stopped”  >&2 

P.S. There must be a space between if  [  condition  ].

read -p “Enter 1st string: ” str1
read -p “Enter 2nd string: ” str2
if  [  $str1 == $str2  ]; then
echo “Both strings are same”
exit 0                                                    #exit 0=success; Exist status value range: 0-255
elif  [  $str1 != $str2  ]; then
echo “Both strings are different”
exit 1                                                   #exit 1=Unsuccessful; Use echo $? to check value

read -p “Enter a file or a directory name: ” file
if  [ -f $file  ]; then
echo “$file exists and is a file”
elif  [ -d $file  ]; then
echo “$file exists and a directory”

2. if, elif and else
# There must be a single space after ‘if’ | ‘elif’ and ‘[‘, and inside the expression

if  [  $# -eq 1  ]; then   #Can use double ‘[[  ]]’ parenthesis as well
echo “Nos of arguments are one: $1
elif  [  $# -eq 2  ]; then
echo “Nos of arguments are two: $1, $2
echo “Nos of arguments: $#”             (Show number of arguments entered)
echo “All argument values: $*”        (Show all arguments in single line)
echo “All argument values:” $@”     (Show all arguments in separate lines)
echo “Script name: $0”                      (Show script name)
echo “Script exit code is: ” $?           (Command or script exit status code, Success=0)

3. for
for i in 1 2 3 4 5; do
echo $i

for i in file{1..5}; do
echo $i

read -p “Enter the number to calculate factorial: ” num
for  ((i=2; i<=$num; i++)); do
fact=$[fact * i]
echo “$num factorial is: ” $fact

for file in $HOME/*; do
echo $file


for EVEN in $(seq 2 2 10); do       #Odd-> $(seq 1 2 10)
echo $EVEN

4. while
read -p “Enter a number: ” num
while [ $num -gt 1 ]; do
fact=$[fact * num]; num=$[num – 1]
echo “Factorial: $fact”

5. untill
read -p “Enter a number: ” num
#CONTINUE until $num is less or equal to 1 or STOP when expression is true
until [ $num -le 1 ]; do
fact=$((fact * num)); num=$((num – 1))       (Can used $[] as well)
echo “Factorial: $fact”

5. case:
#Functions must be defined at the top or before they are called
func1 () {
echo “$1! from func1()”
func2 (){
echo “$1! from func2()”
read -p “Enter function number [1-2] ” n
case $n in
1) func$n Hi;;               #’Hi’ is a parameter/argument to function
2) func$n Hello;;          #’Hello’ is a parameter/argument to function
3|4) echo “You entered either 3 or 4”
*) echo “ERROR: Invalid function number”;;  >&2        #Redirects to stderr

6. functions:

  1. Create a file with the following:
    echo “Shaking…”
    sleep 1
    value=”$[ $RANDOM % 3 ]”         ($[] = $(()) both used for expressions only)
    case $value in
    0) echo “All sign points to yes.” ;;
    1) echo “The answer is no.” ;;
    2) echo “Ask again later.” ;;
    *) echo “Outlook hazy.” ;;
    export -f 8ball             (It will export the function to the shell)
  2. Add the function in script into .bashrc file:
    echo “~/” >> .bashrc; source .bashrc
  3.  Test the function:



About Ishtiaque

I am IBM Certified Infrastructure Systems Architect, Linux Foundation Certified System Administrator, Oracle Certified Programmer in Java and Web Component Developer, and TOGAF 9 certified with over 10 years of support and development experience in IBM middleware software and Java. Additionally, have a sound grip in databases and OpenStack administration. I hold the following certifications: IBM Certified Infrastructure Systems Architect Linux Foundation Certified System Administrator (LFCS) TOGAF 9 Certified Oracle Certified Expert, Java EE6 Web Component Developer Oracle Certified Professional – Java 6 Programmer ITIL v3 Foundation Certified IBM Certified Solution Architect – Cloud Computing Infrastructure V1 IBM Certified System Administrator – WebSphere Portal V8, V7, V6.1, V6 IBM Certified System Administrator – WebSphere Application Server V7, V6.1 IBM Certified System Administrator – AIX V7 IBM Certified System Administrator – WebSphere MQ V7 IBM Certified Deployment Professional – Business Process Manager Advanced V7.5 IBM Certified Solution Advisor – Cloud Computing Architecture V3 IBM Certified Solution Developer – WebSphere Portal V5.1
This entry was posted in LFCE, LFCS, Linux, Scripts. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s