I have a script used for installing few rpms depending on operating system type. Here in this example, the script will install packages on two system "centos" and "suse". The system names are listed in nodes.txt and read as an input while executing the script.
For example:
~]# cat systems.txt
centos
suse
~]# ./myscript.sh systems.txt
There are two scripts written which does the same purpose. One is written using "if-else" and other using "case".
When I use "if-else" condition script, the execution (i.e installation of rpms) completes much faster than using the "case" condition script. Both scripts does the same job, except that the control structure is different. I will have many hundreds of installation criteria listed in the script, and will add/remove new system types within systems.txt file.
Hence I am not sure which condition is better to choose, and considering my use case. Can someone help me know why does case script taking more time to execute when compared if-else? Any help/recommendations?
Below the case script which took 10 secs to complete.
#! /bin/bash
while read -d $'\n' -r node
do
# Each node has a unique id assigned and used along with install script
id=$(./name.sh -getid)
case $node in
centos)
echo $(./install.sh --resourceId=$id --name=httpd)
echo $(./install.sh --resourceId=$id --name=gcc)
;;
suse)
echo $(./install.sh --resourceId=$id --name=compact)
echo $(./install.sh --resourceId=$id --name=glib)
;;
*)
echo "#No resources found for the node"
;;
esac
done < "$1"
Below the if-else script which took 5 secs to complete:
#!/bin/bash
while read -d $'\n' -r node
do
# Each node has a unique id assigned and used along with install script
id=$(./name.sh -getid)
if [ $node == centos ]
then
echo $(./install.sh --resourceId=$id --name=httpd)
echo $(./install.sh --resourceId=$id --name=gcc)
elif [ $node == suse ]
then
echo $(./install.sh --resourceId=$id --name=compact)
echo $(./install.sh --resourceId=$id --name=glib)
else
echo "#No resources found for the node"
fi
done < "$1"
case
will be doing pattern matching, and[ x == y ]
is checking for string equality. With no wildcards,case
may well be optimized. You'd have to check the bash source. \$\endgroup\$