loading...

Writing your first bash script

manabl profile image Manuel Blanco ・4 min read

Bash scripting is an extremely useful and powerful part of system administration and development. It might seem scary the first time you do it as it was for me but bear with me as this is not meant to be an extensive guide to bash scripting, but just a straightforward guide to getting started with making your first script and learning some basic bash syntax.

Bash is a Unix shell, which is a command-line interface (CLI) for interacting with an operating system (OS) is available by default on Linux and macOS operating systems but it can also be turned on as a feature on Windows 10. Any command that you can run from the command line can be used in a bash script and the other way around too.


Requirements

  • A basic command line knowledge is required. Although I'll be explaining what command does what, as I go.

Goals

In this tutorial, we're going to:

  • Create a bash script that can be run from any directory on the computer.
  • Learn about variables, conditions, looping, and user input with bash.

I'll be using /Users/mblanco for all examples, but it will be /Users/your_username for you. So without anything more to say let's get into it

1) Create a bin directory

The first step is to create a bin directory. bin is the standard naming convention of a subdirectory that contains executable programs.

You can make sure you're in the main user directory by navigating to ~ with cd ~ (cd stands for "change directory" and ~ is a shortcut for current user home directory, or /Users/mblanco). You can type pwd to confirm your current location, as well.

Create a bin folder.

cd ~      # this takes us to /Users/mblanco
mkdir bin # this creates /Users/mblanco/bin

2) Export your bin directory to the PATH

Open the file .bash_profile by typing .bash_profile, which will be located at /Users/mblanco/.bash_profile, and add this line to the file. If .bash_profile doesn't exist, create it.

export PATH=$PATH:/Users/mblanco/bin

3) Create a script file

Go to your bin folder located in /Users/mblanco.

cd bin

Create a file called hello-world with no extension.

touch hello-world

Open the file in your text editor of choice and type the following.

#!/bin/bash

A bash script must always begin with #!/bin/bash to signify that the script should run with bash as opposed to any other shell.

#!/bin/bash

echo Hello, World!

4) Execute the bash file

We can run the file in the terminal with hello-world. If it doesn't work we have to make it an executable file by changing the permissions chmod u+x hello-world. When you run the command, it will output whatever you put after the echo

mblanco@dev:~/bin

$ hello-world

Hello, World!

Congrats!! We just made our first bash file :)

Variables

A variable is declared without a $, but has a $ when invoked. Let's edit our hello-world file to use a variable

word = "world"
Hello, $word!
mblanco@dev:~/bin

$ hello-world

Hello, world!

Strings do not need to use single or double quotes by default. However, single and double quoted strings work as well. A single quoted string will not interpolate variables, but a double quoted string will

Taking user input

We declared a variable in the last example, but we can also have the user set the value of a variable dynamically using the read command so instead of having the script to say Hello, World!, we can ask the name of the person calling the script and output that name

#!/bin/bash

echo Who is this?

read who

echo Hello, $who!
mblanco@dev:~$ hello-world
Who is this?
Manuel
Hello, Manuel!

Conditionals

According to Wikipedia:

Conditionals are features of a programming language, which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false

Although bash is not a programming language but a command-line interface (CLI), you can do conditionals with it too. Here you can use if statements with the following keywords: if, then, else, and fi. With the condition inside square brackets.

We can create another file or edit the previous example, as you prefer, and copy/paste the following:

#!/bin/bash

echo Are you sure you are allowed to drink kid? How older are you?

read age

if [ "$age" -ge 18 ]
then
    echo You are just fine. Drinks up! 🍻
else
    echo Get out of here! 🏃🏻
fi
mblanco@dev:~/bin

$ hello-world

Are you sure you are allowed to drink kid? How older are you?
20
You are just fine. Drinks up! 🍻

Here's a list of operators for you to try different things:

Bash Operators Operator Description
-eq == Equal
-ne != Not equal
-lt < Less them
-le <= Less them or equal
-gt > Greater them
-ge >= Greater than or equal
-z ==null` Is null

Looping

We'll create a version of the command ls (which makes a list of all the files and directories in your current address) but this one will only give us the names of the files.

`

!/bin/bash

FILES=/Users/mblanco/projects*

for file in $FILES
do
    echo $(basename $file)
done


`


Conclusion

I hope this article has been helpful for you guys to get started with bash and see you next time🤘👋

Posted on by:

manabl profile

Manuel Blanco

@manabl

Front End Dev working at Infrapedia Inc.

Discussion

markdown guide
 

Most helpful for beginners.
Check enlight.nyc
Tell me what you think of it.
Thanks