Write Programs in Linux Bash

Although Linux distributions are always easier to use, it happens sometimes having to resort to the shell and hence the average user stops and says that Linux is a system for experts. In this article I will speak of shell programming in a world like that of the penguin is always useful. There are various types of shell, here we will talk about sh (Bourme Shell) which later evolved in bash, which is perhaps the most widely used today. In Linux a file is executable when it has certain bits set and by extension, to make esguibile a file must use the command:

chmod + x filename

But it must be executed with ./filename unless it gets in path:

export PATH = $ PATH:/directory/filename

In fact, with export export the variable in the general path without write startup files and only applies in the window of the current shell.

Comments are like those of C // o /* */, while the variables have the operation of those with php $front ($total) for the value, but nothing for the assignment (total = 10) . There are special variables like $1 – $2 … which are simply the arguments of the command line, the first, second and so on. The shell commands are written as they are, for example if we write

cp -i $1 $2

copies the first on the second parameter of the command line. Some characters have special value to the shell and must be used carefully, for example if I write

vi * I will edit all files in the current directory, while you vi \* will only open the file named *

in slang is called to do the quoting of special characters. But we see some practical examples of shell programming:

#/bin/sh/
age = 24
echo ‘My age is’ $age

this little program on the shell writes, “My age is 24” because it is the echo command to write. String literals should be in quotes. 

#/bin/sh
a = 5
b = 8
tot = $a + $b
if $tot > 10 -a $tot < 20 then
    echo $tot
fi

this instead writes the total sum only if the value is between 11 and 19. Logical operators are-a (AND)-or (OR)! (NOT).

As in other languages if there … else … fi always remember to close with fi if! There is also a while do … done and then the loop in an example, write the numbers 1 to 10.

#/bin/sh
for i in 1 2 3 4 5 6 7 8 9 10
do
    echo $i
done

To debug using the echo and makes the output values of the variables on the shell, perhaps with the current line to find out where the error is because you can write real programs with the shell, use the less command on some startup files and you will realize what it means! We have seen how Bourme Shell can be used to plan, certainly not at the level of C or Perl or Java, but may be suitable for some tasks, such as compiling source packages on the fly to a distribution like Arch Linux.

This entry was posted in Linux. Bookmark the permalink.