Bash scripting(I)

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"

This is the first article of a series focused in Gnu Bash scripting. It’s not a complete course on bash programing, but at the end you should learn one or two things. I mean, useful things that’ll help make your life easier.

Laziness is the key to succeed

Sometimes I need to run command1, followed by command2, then command3 and finally command4. After a while I need to repeat that command sequence. But as I am very smart I went through command history with the arrow up key so I don’t to write all over again.

Then, after other while, I have to do it again, and I’m know that I will have to do it again several times in the future. For example, every day, you boot your computer, log on your debian-based linux and check for package upgrades:

# apt-get update
(...)
# apt-get upgrade
(...)
# apt-get dist-upgrade

Instead of typing those 52 chars every time, you could put it on a script like this:

#!/bin/bash
#this is not a Hello world
apt-get update
apt-get upgrade
apt-get dist-upgrade

You can save this script as ‘up.sh’ and next morning after you login just run: ./up.sh . Just like that you’ve saved 44 keystrokes, are you getting lazy or what?.

No, we aren’t, if you try to run ‘as is’, you’ll get a beautiful Permission denied error. That’s because I’ve never told to set execution permission:

# chmod +x up.sh

Later I’ll show you how to be even more lazy.

Besides the commands on the last lines, you’ve noticed the number character (#) on the first two lines. The very first line is called shebang and tells the system which interpreter use to run the commands on the script.

The second one is just a comment and you can put it everywhere: what comes behind that sign will be ignored. For example:

# this is a comment
command1 # this also is a comment. Should explain what that command do
#command2. # This was command... but as was commented out, bash would ignore it

It’s important (to me at least) to add at least a couples of comments to remember you what the script does and why. Also, in large scripts, to add comments to explain blocks, or sections, or parts of the script. Comments will help you when you get back to your script a some months, or weeks, or even days later.

Getting more lazy

There is no need to type every time we log on our systems. We can make the computer run that script for us. You can add the line “./up.sh” on one of the following places:

  • .bashrc . This will run the script every time you launch a non-login shell (i.e. the terminal included on your desktop, like xterm)
  • .bash_profile This is for login shell, for example when you type your user and password on the console or log in your system vía ssh.
  • .xinitrc like .bashrc but for graphical sessions. You are probably using a modern destkop with it’s own tools to autostart applications, use them.
  • an entry in your crontab file, so it runs periodically.

Variables

We need ‘something’ to store values, for example user input, a parameter from the command line. This ‘something’ is a variable. By the way, I’m assuming that you already know what a variable is.

To declare a variable, you can

  • assign a value to a variable name. Example: x=1
  • input the user for a value with the read command: read x
  • a parameter from the command line. I’m going back to this really soon
  • the are other ways to define a variable that we will see later

To ‘call’ a variable type the dollar sign followed by the variable name. For example if we want to print in the screen the value for the $x variable:

echo "x value: $x"
echo "Type y vaue:"
read y
echo "You typed: $y"

Command line parameters are stored in numbered variables. For example, the use the first argument, call the $1 variable. For the 2nd, call $2. And so on. The variable $0 stores the script file name. In my first not-a-hello-world example the value for $0 is “up.sh”.

Arrays

Arrays are defined the same way, but with the values enclosed between round brackets. Like this:

array=(uno dos tres)

You can add later more values to the array with the index enclosed in square brackets:

array[3]=cuatro

You can ‘call’ an array element with curly bracket for the array name, and square bracket for the element position (starting with 0):

$ echo ${array[0]}
uno

If you don’t use the curly bracket, bash will print a literal [element position], for example:

$ echo $array[0]
uno[0]

You can call all the array with an @ as index like this:

$ echo ${array[@]}
uno dos tres cuatro

Finally you can get the number of elements of an array with the hash sign (the same one I’ve told before it is for comments) like this:

echo ${#array[@]}
4

There are a lot of other things we can do with arrays, and other array types, like associative arrays. But this is enough for today.

Stay tuned

So far I didn’t showed anything very “woaaah“. There isn’t even a single screenshot in this article. But my intention toward the end of this -maybe three or more articles- series is to give tools to do something useful. I don’t know if you will become a bash scripting guru, but you can try 😉

On the next one I’ll cover some control structures, pipelines, and redirection. In the meanwhile you can check the bash manpage, but at least to me is a little bit confusing

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"
Gonzalo Rivero
Gonzalo Rivero
I am Gonzalo, I live in Salta, a city located in the NW of Argentina. I play the guitar and a little harmonica. I also like to bike.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest articles

Join us on Facebook