Programming in bash - part 1

While we generally use it for administrative or file management operations, the comfort de Linux extends its functionality far beyond that purpose, allowing us to program scripts This guide is not intended to be a complete reference on Bash programming, but rather an introduction to the basic commands and structures, which will allow us to expand the power of our GNU / Linux system.

What is a "Script"?

Basically we say that it is a file that contains code written in a certain programming language that the system uses for a certain task. It does not need to have an external input or graphical interface, but it does need to cause an output of processed data (even if the user does not see it).

The language used by Bash is defined by its own interpreter and combines the syntax of other Shells, such as the Korn Shell (ksh) or the C Shell (csh). Many of the commands that are usually used in the console can also be used in scripts, except those that strictly pertain to a particular distribution.

Structure of a Script

To begin we must have a text editor and desire to program. The files that we save with a .sh extension can be executed (or interpreted) by the console, as long as the first line is the following:

#! / Bin / bash

This tells the system to use the console to run the file. Also, the # character allows you to write comments. To create the simplest example we add one more line, seen in the following image:

The echo command displays a message on the screen, in this case the typical "Hello world!" If we save it and execute it with the console we will see the result.

Basic Commands

The following commands are common and very useful for any type of program. We clarify that there are many more, but for now we will cover the following.

Aliases: allows a string of words to be replaced by a shorter one, allowing code reduction.

#create an alias called per with the address of the #Downloads folder alias per = '/ home / user / Downloads' #Every time we want to use it we just have to call #the new word per #To destroy that alias, we use unalias unalias per

break: allows to immediately exit a for, while, until or select loop (we will study loops in detail later)

#Create a loop that will assign the numbers from 1 to 5 #for each "turn of the loop" for counter in 1 2 3 4 5 do #We print the current value of the variable #counter, which is analyzed by the character $ echo " $ counter ”#If the counter value is equal to 3 if [$ counter –eq 3] then #The break exits the loop for break fi done

continue - Similar to break, except that it ignores the current loop and goes to the next one.

#Create a loop that will assign the numbers from 1 to 5 #for each "turn of the loop" for counter in 1 2 3 4 5 do #If the counter value is equal to 3 if [$ counter –eq 3] then #Continue prevents the rest of the current # cycle from being analyzed by jumping to the next round, that is, #value 3 will not be printed. continue fi echo "$ counter" done

declare: declares variables and assigns them values, just like typeset (they work the same way). We can combine it with some options: -i declares integers; -r for read-only variables, whose value cannot be changed; –A for arrays or “arrays”; -f for functions; -x for variables that can be "exported" outside the environment of the script itself.

declare –i num = 12 declare –x pi = 3.14

help: shows help for a specific command.

jobs: shows the running processes.

#With –c we show the name of the commands, with –p # the pid (process id) of each process. jobs -cp

let: evaluate an arithmetic expression

let a = 11 let a = a + 5 #Finally we print the value of a which is 16 echo "11 + 5 = $ a"

local: create local variables, which should be used preferably in functions of the script itself to avoid errors. You can use the same functions as the declare command.

local v1 = "This is a local variable"

logout: allows logging out of a Shell completely; useful for cases where we work with more than one shell window, in which the exit command will only allow one window to be terminated at a time.

printf: allows you to print data and format it. It has many options, so we will mention a few.

#% f prints as a floating number, n for new # line printf "% fn" 5 5.000000 # & d allows to pass decimal numbers as arguments printf "There are% d orders valued in% d dollars.n" 20 500 There are 20 orders valued at 500 Dollars.

read: read a line from standard input (module used in loading data through the keyboard for example). We can pass options like: -t to give a reading limit time; -a so that each word is assigned to a position in the aname array; -d to use a delimiter that will be written at the end of the line; among others.

echo "Enter your name and press ENTER" #Read the variable name read name echo "Your name is $ name"

type: describes a command and its behavior. It can be useful to find out the data definitions for each command.

type –a '[' #type tells us that [is a Shell builtin command [is a Shell builtin # -a allows to find the directories that contain # an executable with the written name. [is / usr / bin / [

ulimit: limits the access and use of certain system resources to processes, ideal for programs that allow administrative changes or that are aimed at different types of users. When setting a limit we write a number that represents the kilobytes of the limit.

#We see our current limits ulimit –a # -f allows limiting users to not be able to # create files larger than 512000 Kb (500 #Mb) ulimit –f 512000 # -v limits the virtual memory of the process. ulimit –v 512000

wait: wait for a certain process or job to be carried out to continue.

#The script waits for the process of pid # 2585 to be carried out

wait 2585

Other useful commands that we can add to scripts are represented by symbols.

!!: run the last command again

! wer: executes the last command that started with the expression “wer”.

'==', '! =', '>', '<', '> =', and '<=': relational operators.

|: The OR operator generally used to join two regular expressions.

: escape command that allows you to format expressions. For example: a for a sound alert, n for newline, b for backspace, etc.

Thank you Juan Carlos Ortiz!

Add as preferred source