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!

The content of the article adheres to our principles of editorial ethics. To report an error click here!.

10 comments, leave yours

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   Medium Difficult said

    Great! Anyway 2 comments: The Ubuntu tag is half too many, as it generalizes something that is generic. And if these tutorials continue to advance, it would be good if they are linked to each other….
    Other than that, this move is interesting!

  2.   Let's use Linux said

    Good contribution! Great!

  3.   Giovanni escobar sosa said

    Only missing references for those who want to get more into the matter. Some good ones although not so easy to find in our countries are
    - A practical Guide to Linux Commands, Editors, and Shell Programming, Mark Sobell (Chapter 8)
    - Pro Bash Programming, Chris FA Johnson (although this is for those who have other references or a little more knowledge).

    Good article.

  4.   Let's use Linux said

    Good date! Thank you!

  5.   Patricio Dorantes Jamarne said

    : @ The "log in as" function deleted my previous comment, so I'll summarize it further:
    jobs -cp
    bash: jobs: -c: invalid option
    jobs: usage: jobs [-lnprs] [jobspec…] or jobs -x command [args]

    -eq -gt -lt do not accept decimal point variables, between forum and forum I discovered that bc is a good ally:
    if [`echo 9.999> 10 | bc` -eq 1]; then
    echo "9.999 is greater than 10, make sure your processor is still working"
    else
    echo «9.999 is not greater than 10, everything works normally
    fi

  6.   NotFromBrooklyn said

    This post summarizes very well all the generalities of bash scripting:
    http://www.aboutlinux.info/2005/10/10-seconds-guide-to-bash-shell.html

    On this site you will find many questions and answers about bash peculiarities:
    http://unix.stackexchange.com/questions/tagged/bash

    Here are some really cool scripts, and hey, you can learn them by reading other people's scripts:
    http://snipplr.com/search.php?q=bash&btnsearch=go

  7.   NotFromBrooklyn said

    You are right with what you say, except for bash. Every system I've seen has bash in / bin / bash.

    But for python, perl, ruby, etc, it's fine to use that. I do

  8.   Guille said

    Coincidentally, in college we are using bash scripting so the data is 10, very good!

  9.   alex i saw said

    a pdf version to download would be good !! 😀

  10.   Marco Antonio De Fuentes said

    Very good site. I finally found something useful. Thank you.