How To Use Bash and Stay Alive

A useful guide on how to automate common simple, repetitive, and sometimes boring actions using Bash.

Rajat S
Bits and Pieces

--

Bash is a Unix shell and command language that was built for the GNU Project as a free software. It was created as a replacement for the Bourne shell sh. In fact, Bash is an acronym for “Bourne Again Shell” 😆.

Originally launched in 1989, Bash today is compatible with multiple operating system like Linux, Mac OS, Windows 10, and Solaris 11.

If you are not familiar with what a shell is, it is simply a macro processor that executes commands.

The shell provides the UI to the rich set of GNU utilities and the programming language features allow these utilities to be combined. This allows us to create files full of commands, or turn such files into commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users to establish custom environments to automate their common tasks.

It is never fun to perform simple tasks. Our need to escape the responsibility of performing such tasks has led to many important discoveries and inventions. *Cough* Computers *Cough*.

In this post, we will take a look how to escape the need to perform boring repetitive tasks in web development by automating them using Bash.

Note: Bash is officially supported in Windows 10, Mac OS, Linux, and Solaris 11 operating systems.

Downloading Bash

Bash can be found on:

Once you have properly installed Bash on your system, open the command terminal and you will notice the tilde ~ character. ~ represents the user’s current home directory and means that Bash has been properly installed and we can get started.

Navigating the Filesystem in Bash

Let’s start with something very simple — finding your current location. In your command terminal run the command pwd.

$ pwd
/Users/rajats

pwd stands for “print working directory”, and that is exactly what this command does — it gives us the absolute file path of our current working directory.

If you want the terminal to print out a list of subdirectories that are present inside the home directory, then run the command ls.

$ ls
// list of subdirectories

If you want to change the current directory, you can run the command cd, which stands for “change directory”. Use this command follow by the name of any folder that is present inside your home directory.

$ cd <folder name>
<folder name> rajats$

The ls command gives us a simple plain list. If you want the terminal to print out some extra information, then you need to pass the flag -l alongwith the command ls like this:

$ ls -l
// a detailed list of subdirectories

To see any hidden files and folders, we need to pass the flag -a to the ls command:

$ ls -a
// list of subdirectories containing hidden files as well

In your list of subdirectories, you will see a folder with a single dot . and another folder with double dots ... The folder with the single dot is the current directory and the folder with double dots is the parent directory.

If you run the command cd .., you will be taken to the parent directory.

View Files in Bash

Instead of opening files separately, we can use Bash to open them in the terminal itself, or at least tell Bash to open it for us using a certain application. An example of this would be when you run the command code . to open the Visual Studio Code application.

To open a simple file in the terminal itself, Bash has provided us with the command cat.

$ cat <filename>

This will dump all the content of that file on your terminal. If the file you are viewing in terminal is some kind of text file, and you want Bash to give its content in a proper format, you can pass the -n flag to the cat command and you will now get line numbers in your terminal.

$ cat -n <filename>

But if your file is too long, adding line numbers won’t really improve your experience of viewing the file in the terminal. This is why Bash has given us another similar command called less.

$ less <filename>

With this, Bash will print the contents of the file onto the terminal, and keep the pre-existing formatting of the file as it is. It will also clear the content of the terminal before displaying the contents of the file.

less can do more than just display the contents of the file. If you press Shift + G your cursor will move to the end of the file. Pressing G will take you the top of the file.

You can also search through the contents of the file. Type / followed by some keyword that you want to search.

/<keyword>

This will highlight all instances of the keyword in your file. If you want to go back to the normal terminal, just press Q.

Opening a folder using Bash is pretty simple. Just type the command open followed by the name of the folder. 😛

$ open <foldername>

To tell Bash to open the file or folder with a particular application, you need pass it the -a flag as shown below.

$ open <filename> -a <applicationname>

Create and Delete Files

To create a file using Bash, we need to use the touch command as shown below:

$ touch <filename>

Make sure that you mention the extension of the file when using this command.

$ touch file.txt

This command will create a simple but empty text file. To add content to this file through the terminal itself, use the echo command as shown below:

$ echo 'hello world' > file.txt

This will send the string hello world into the file itself. The only drawback of this command is that writing another echo will overwrite the previous one. But this can be easily solved. Just replace > by >> and Bash will append the string to your file.

To create a folder requires us to use another command called mkdir as shown below:

$ mkdir rajat

This will create a folder called rajat in your directory. To delete this folder, simply run the command rm as shown below:

$ rm rajat

Note that rm will complete delete the folder/file from your system. If you want to send this file to the trash instead, you need to pass the flag -r to rm command. If you pass another flag -f with it, then the system will not bother sending you any confirmation prompts.

$ rm -rf rajat

Copy and Move Files using Bash

Till now, we have seen how to create, edit, and delete files using Bash. All that is left to see is how to copy and move files using Bash.

Bash’s mv command allows us to move files from one place to another.

$ mv file.txt <destination>/file.txt

Similarly, we have the cp command to copy files as shown below.

$ cp file.txt <destination>/file.txt

If you want to copy an entire folder along with its sub-folders, you need to pass the -R flag to the cp command. -R stands for recursive.

$ cp -R <foldername>/* <destination>/ 

Find things in Bash using “find”

In Bash, we have another command called find that can not only find files and folders for us but it can also run a command on each of the search results.

In my current directory I have created a folder called hero which contains a few images of superheroes.

$ ls images
superman.png batman.png spiderman.jpg

If I wanted to find all the image files that have the extension of .png, I can use the find command as shown below:

$ find images/ -name "*.png"
images//superman.png
images//batman.png

The -name flag will case sensitive. If we want our search to not bother with uppercase and lowercase names, we can replace the -name with -iname flag.

The find command also supports actions. For example, if I wanted to delete the superman.png file, all I have to do is pass the -delete flag to find as shown below:

$ find images/ -name "superman.png" -delete
$ ls images/
batman.png spiderman.jpg

Make HTTP Requests in Bash with “curl”

In Bash, we use the command curl to make any HTTP requests directly from the terminal. This is extremely helpful while testing APIs as it lets us have complete control over any headers that we send without having to working on any kind of user interface.

Go to your command terminal and run the following curl command:

curl http://swapi.co/api/people/1/

The given URL refers to the infamous Star Wars API. Since its an api, the response to the above curl command will in the form of a JSON file as shown below:

{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}

But this not exactly helpful. We would also need to inspect the headers of the response. For that, we need to pass the flag -i to the curl command as shown below.

$ curl -i https://swapi.co/api/people/1/

Make sure that you add the trailing / to the URL. Doing so will allow curl to follow any redirects. Another method of telling curl to follow any redirects would be to add the -L flag to the command.

Bash Scripts

Bash also allow us to add logical data that can be later executed in a script. Bash Scripts are special files with the extension of .sh. Let’s create one using the command touch.

$ touch rajat.sh

Bash comes with its own text editor called nano. I will use it to add some content to the script file we just created.

$ nano rajat.sh

Inside write a simple echo command as shown below:

echo "hello world"

Now, to execute this file, all we need to do is type ./rajat.sh. But this will not work, yet.

Even though we have created the file, we do not have the permission to execute it. So to give us the permission to execute it, type:

$ chmod u+x script.sh

Type ./rajat.sh again and you will see that it now executes as we wanted it to.

$ ./rajat.sh
hello world

We can also pass variables to our Bash scripts. Get back into the nano editor and rewrite the echo command as:

echo "$1"

Here, $1 is our variable. In Bash, we need to reference values using argument numbers. Now while executing the Bash script, pass in the value that you want the variable to refer to as shown below:

$ ./rajat.sh "rajat"
rajat

Let’s take a deeper look into Bash variables in the next section.

Bash Variables

Bash is a programming language. So like any other programming language, it should also be able to define variables.

Let’s create a very simple variable called writer and give it a string value. Use echo to verify that a variable named writer has been created.

$ writer="rajat"
$ echo $writer
rajat

Note: Make sure that there are no spaces while defining the variable. Else, the terminal will assume that writer here is some unknown command and throw some error.

The writer variable is only defined for the current Bash session. Meaning, if you restart the command terminal, writer will be undefined again. It will not be defined for any Bash scripts. For example, create a new script file using touch, and write echo $writer inside it using the nano text editor.

$ touch rajat.sh
$ nano rajat.sh
// echo $writer
$ chmod u+x rajat.sh
$ ./rajat.sh
// you will get a blank output here.

To solve this problem, all we need to do is write export writer. This command will make the variable visible to all Bash Scripts in your system and if you execute the Bash script again, you will get the proper output.

$ export writer
$ ./rajat.sh
rajat

If you want to unset the definition of the variable. All you need to do is type unset <variable name>.

Functions in Bash

More than just variables, we can also write functions in Bash. Bash functions are nothing but a smaller version of a Bash script. To understand how Bash functions work, lets start by creating a new Bash Script and giving it execution permissions using chmod as shown below:

$ touch rajat1.sh
$ chmod u+x rajat1.sh
$ nano rajat1.sh

Then write the following function that simply echos a string:

rajat() {
echo "rajat"
}
rajat

To execute this function, all we need to do is type ./rajat1.sh.

Exit Status

Every command, script and function in Bash has an “exit status”, which a number between 0 and 255. This number represents the status of the command — whether it executed successfully or failed miserably.

Lets take a look at one of the simplest commands in Bash — ls. First we need to run this command in our terminal.

$ ls

Next we need to echo a special variable ?. Doing so will return us the exit status of the previous command, which in this case was the ls command.

$ echo $?
0

If you were return a value of 0, then it means that the ls command was executed successfully!

The value of 1 refers to a general error and the value of 130 infers that the command was aborted by the user before its completion.

In case of scripts, we can explicitly set their exit statuses. Just enter the nano text editor and type exit followed by a number between 0 and 255.

If the exit status for a script is not explicitly set, then Bash will assume it to be 0.

Wrapping Up!

Bash is not something new. It has been around for a long time. So long that even this long post has not fully covered all the features and uses of Bash completely.

If you want to learn more about what Bash can do for you, check out its official doc here:

Thanks for reading! Please 👏 if you liked this post! If you think I have missed out some important feature of Bash, let me know here or on Twitter.

Shared with ❤️ in Bit’s Blog

Bit’s platform turns components into building blocks which can be easily shared, used and developed in any project. Give it a try to build new applications faster with your team. It’s open source.

--

--