(RHCSA) Create Simple Shell Scripts

This is part of the RHCSA Exam Study Guide series

image

This is part of the independent and unofficial RHCSA Exam Study Guide series providing free šŸ¤‘ resources to prepare for the exam.

This post covers the objectives under the section:

“CREATE SIMPLE SHELL SCRIPTS”

It contains two main parts:

  • Resources: with links to learn and practice for each objective.
  • Cheatsheet: containing some examples of commands and actions performed in each objective (when applied).

šŸ“š Resources:

CONDITIONALLY EXECUTE CODE (USE OF: IF, TEST, [], ETC.)

USE LOOPING CONSTRUCTS (FOR, ETC.) TO PROCESS FILE, COMMAND LINE INPUT

PROCESS SCRIPT INPUTS ($1, $2, ETC.)

PROCESSING OUTPUT OF SHELL COMMANDS WITHIN A SCRIPT

PROCESSING SHELL COMMAND EXIT CODES


šŸ“‘ Cheatsheet:

CONDITIONALLY EXECUTE CODE

#!/bin/bash

if [ "$(uname)" == "Linux" ]
then 
    echo "OK"
else 
    echo "nah"
fi
#!/bin/bash

if test "$(uname)" == "Linux"
then 
    echo "OK"
else 
    echo "nah"
fi

USE LOOPING CONSTRUCTS (FOR, ETC.) TO PROCESS FILE, COMMAND LINE INPUT

#!/bin/bash

ls "$1" > files.tmp

while read filename
do
    echo "$(basename $filename | cut -d '.' -f 1)"
done < files.tmp

rm files.tmp

PROCESS SCRIPT INPUTS ($1,$2, ETC.)

#!/bin/bash

COUNTER=1

if [ "$#" -gt 0 ]
then
    for i in "$@"
    do
        echo "Argument $COUNTER is $i"
        ((COUNTER++))
    done
else
    echo "No arguments passed to the script."
fi

PROCESSING OUTPUT OF SHELL COMMANDS WITHIN A SCRIPT

#!/bin/bash

for i in $(find . -maxdepth 1 -type f)
do      
    echo "filename is: $(echo $i | cut -c 3-)"
done    

PROCESSING SHELL COMMAND EXIT CODES

#!/bin/bash

date | grep Sun

if [[ $? -eq 0 ]]
then
    echo "Go to the beach, it's sunday" 
    exit 0
else
    echo "Please get back to work"
    exit 1
fi

Next:

(RHCSA) Operate Running Systems

…or back to Red Hat Certified System Administrator (RHCSA) Exam Study Guide



Footnotes:

  • Follow me on Twitter to get more posts like this and other quick tips in your feed.
  • If you have any doubts or tips about this article, Iā€™d appreciate knowing and discussing it via email.
  • Do you have any other Linux tips? Would you like to publish that in this blog? Please send an email to all drops.
  • As English is not my native language, I apologize for the errors. Corrections are welcome.
  • Contact: contact [@] alldrops [.] info.

Read more on linux drops: