<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>shell scripting Archives - Tech Chronicles</title>
	<atom:link href="http://kostacipo.stream/tag/shell-scripting/feed/" rel="self" type="application/rss+xml" />
	<link>http://kostacipo.stream/tag/shell-scripting/</link>
	<description>Ramblings of a Tech Dude</description>
	<lastBuildDate>Fri, 17 Jan 2020 11:05:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.2</generator>

<image>
	<url>https://kostacipo.stream/wp-content/uploads/2019/12/cropped-profile-32x32.jpg</url>
	<title>shell scripting Archives - Tech Chronicles</title>
	<link>http://kostacipo.stream/tag/shell-scripting/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How To Create a Foolproof Shell Script</title>
		<link>http://kostacipo.stream/how-to-create-a-foolproof-shell-script/</link>
					<comments>http://kostacipo.stream/how-to-create-a-foolproof-shell-script/#respond</comments>
		
		<dc:creator><![CDATA[Majordomo]]></dc:creator>
		<pubDate>Fri, 17 Jan 2020 11:05:06 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[shell scripting]]></category>
		<guid isPermaLink="false">http://www.kostacipo.stream/?p=1666</guid>

					<description><![CDATA[<p>&#160; I am a (lazy) DevOps Engineer. So whenever I came across the same task more than 2 times, I automate that. Although now we have many automation tools, still the first thing that hit into our mind for automation is bash or shell script. &#160; I would like to share my experiences for writing [&#8230;]</p>
<p>The post <a href="http://kostacipo.stream/how-to-create-a-foolproof-shell-script/">How To Create a Foolproof Shell Script</a> appeared first on <a href="http://kostacipo.stream">Tech Chronicles</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>&nbsp;</p>
<div class="paragraph">I am a (lazy) DevOps Engineer. So whenever I came across the same task more than 2 times, I automate that. Although now we have many automation tools, still the first thing that hit into our mind for automation is bash or shell script.</div>
<div>&nbsp;</div>
<div class="paragraph">I would like to share my experiences for writing a good shell script which not only looks good but also it will reduce the chances of error.</div>
<ul>
<li>A minimum effort in the modification.</li>
<li>Your program should talk in itself, so you don’t have to explain it.</li>
<li>Reusability, of course. I can’t write the same kind of script or program again and again.</li>
</ul>
<div class="paragraph">I am a firm believer in learning by doing. So let’s create a problem statement for ourselves and then try to solve it via shell scripting with best practices :). </div>
<div>&nbsp;</div>
<div class="paragraph"><strong>Problem Statement</strong></div>
<div>&nbsp;</div>
<div class="paragraph">Write a shell script to install and uninstall a package(vim) depending on the arguments. The script should tell if the package is already installed. If no argument is passed it should print the help page.</div>
<div>&nbsp;</div>
<div class="paragraph">So without wasting time let’s start for writing an awesome shell script. Here is the list of things that should always be taken care of while writing a shell script.</div>
<h2>Lifespan of Script</h2>
<div class="paragraph">If your script is procedural (each subsequent steps relies on the previous step to complete), do me a favor and add <strong>set -e&nbsp;</strong>in starting of the script so that the script exits on the first error. For example:</div>
<div class="code-container">
<pre><code>#!/bin/bash

set -e # Script exits on first failure
set -x # For debugging purpose

<span class="hljs-function">install_package</span>() {
    yum install docker
}

<span class="hljs-function">list_docker_images</span>() {
    docker images # depends on success of install_package function
}</code></pre>
</div>
<h2>Functions</h2>
<div class="paragraph">Functions are my most favorite part of programming. There is a saying</div>
<div>&nbsp;</div>
<blockquote><p>“<strong><em>Any fool can write code that a computer can understand. Good programmers write code that humans can understand.</em></strong><em>”</em></p></blockquote>
<div class="paragraph">To achieve this always try to use functions and name them properly so that anyone can understand the function just by reading its name. Functions also provide the concept of reusability. It also removes the duplicating of code. How? let’s see this:</div>
<div class="code-container">
<pre><code>#!/bin/bash

<span class="hljs-function">install_package</span>() {
    local PACKAGE_NAME="$1"
    yum install "${PACKAGE_NAME}" -y
}

install_package "vim"</code></pre>
</div>
<h2>Command Sanity</h2>
<div class="paragraph">Usually, scripts call other scripts or binary. When we are dealing with commands there are chances that commands will not be available on all systems. So my suggestion is to check them before proceeding.</div>
<div class="code-container">
<pre><code>#!/bin/bash

<span class="hljs-function">check_package</span>() {
    local PACKAGE_NAME="$1"
    if ! command -v "${PACKAGE_NAME}" &gt; /dev/null 2&gt;&amp;1
    then
        printf "${PACKAGE_NAME} is not installed.\n"
    else
        printf "${PACKAGE_NAME} is already installed.\n"
    fi
}

check_package "vim"</code></pre>
</div>
<h2>Help Page</h2>
<div class="paragraph">If you guys are familiar with Linux, you have certainly noticed that every Linux command has its help page. The same thing can be true for the script as well. It would be really helpful to include&nbsp;<strong> &#8211;help&nbsp;</strong>flag.</div>
<div class="code-container">
<pre><code>#!/bin/bash

INITIAL_PARAMS="$*"

<span class="hljs-function">help_function</span>() {
    {
        printf "Usage:- ./script &lt;option&gt;\n"
        printf "Options:\n"
        printf "  -a ==&gt; Install all base softwares\n"
        printf "  -r ==&gt; Remove base softwares\n"
    }
}

<span class="hljs-function">arg_checker</span>() {
    if [ "${INITIAL_PARAMS}" == "--help" ]; then
        help_function
    fi
}

arg_checker</code></pre>
</div>
<h2>Logging</h2>
<div class="paragraph">Logging is the most critical thing for everyone whether he is a developer, sysadmin or DevOps. Debugging seems to be impossible without logs. As we know most applications generate logs for understanding that what is happening with the application, the same practice can be implemented for shell script as well. For generating logs we have a bash utility called&nbsp;<strong>logger</strong>.</div>
<div class="code-container">
<pre><code>#!/bin/bash

DATE=$(date)

declare DATE

<span class="hljs-function">check_file</span>() {
    local FILENAME="$1"
    if ! ls "${FILENAME}" &gt; /dev/null 2&gt;&amp;1
    then
        logger -s "${DATE}: ${FILENAME} doesn't exists"
    else
        logger -s "${DATE}: ${FILENAME} found successfuly"
    fi
}

check_file "/etc/passwd"</code></pre>
</div>
<h2>Variables</h2>
<div class="paragraph">I like to name my variables in Capital letters with an underscore. In this way, I will not get confused with the function name and variable name. Never give <strong>a,b,c</strong>&nbsp;etc. as a variable name instead of that try to give a proper name to a variable as well just like functions.</div>
<div class="code-container">
<pre><code>#!/bin/bash

# Use declare for declaring global variables
declare GLOBAL_MESSAGE="Hey, I am a global message"

# Use local for declaring local variables inside the function
<span class="hljs-function">message_print</span>() {
    local LOCAL_MESSAGE="Hey, I am a local meesage"
    printf "Global Message:- ${GLOBAL_MESSAGE}\n"
    printf "Local Message:- ${LOCAL_MESSAGE}\n"
}

message_print</code></pre>
</div>
<h2>Cases</h2>
<div class="paragraph">Cases are also a fascinating part of shell script. But the question is when to use this? According to me if your shell program is providing more than one functionality basis on the arguments then you should go for cases. For example:- If your shell utility provides the capability of installing and uninstalling the software.</div>
<div class="code-container">
<pre><code>#!/bin/bash

<span class="hljs-function">print_message</span>() {
    MESSAGE="$1"
    echo "${MESSAGE}"
}

case "$1" in
    -i|--input)
        print_message "Input Message"
        ;;
    -o|--output)
        print_message "Output Message"
        ;;
    --debug)
        print_message "Debug Message"
        ;;
    *)
        print_message "Wront Input"
        ;;
esac</code></pre>
</div>
<div class="paragraph">In this article, we have covered functions, variables, the lifespan of a script, logging, help page, command sanity.</div>
<p>The post <a href="http://kostacipo.stream/how-to-create-a-foolproof-shell-script/">How To Create a Foolproof Shell Script</a> appeared first on <a href="http://kostacipo.stream">Tech Chronicles</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://kostacipo.stream/how-to-create-a-foolproof-shell-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
