- How to Create and Use Bash Scripts
- Newsletter
- Comments
- About me
- Post Details
- Category
- Tags
- Newsletter
- How to Create a Shell Script in Linux
- What is Shell Scripting in Linux?
- Ways of Creating a Simple Shell Script in Linux
- Method 1: Using the Default Text Editor
- Method 2: Using the Vim Text Editor Tool
- Adding Comments in Shell
- Using Shell Variables
- The Conclusion
How to Create and Use Bash Scripts
Bash scripting is an extremely useful and powerful part of system administration and development. It might seem extremely scary the first time you do it, but hopefully this guide will help ease the fear.
Bash is a Unix shell, which is a command line interface (CLI) for interacting with an operating system (OS). Any command that you can run from the command line can be used in a bash script. Scripts are used to run a series of commands.
Bash is available by default on Linux and macOS operating systems.
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.
Note: Newer macOS installations (from Catalina) come installed with zsh (Z shell) as the new default, but everything in this article will still be applicable.
- A basic command line knowledge is required. Everything you need to know to get started can be found in my How to Use the Command Line article.
This guide was created on macOS, and will be using /Users/you as the default user directory for all examples. However, the concepts here will apply to any Unix-like operating system, including macOS and various Linux distributions.
In this tutorial, we’re going to:
Making a bash script is a lot simpler than you might think.
Create a file called hello-world , using the touch command.
Edit the file with the program of your choice. Within the file, print a string that says «Hello, world!’ using echo .
Now from the command line, run the script using the bash interpreter:
You’ll see the script has run successfully from the output.
That’s it, you’ve created your first script!
So far, you’ve learned how to run a script from the command line prefixed with the bash interpreter. However, if you want to run the script by name alone, it won’t work. Try to run the file simply by typing the name of the file and pressing enter. Note that we’re prefixing the file with ./ , which means a file in the current directory.
bash: ./hello-world: Permission denied
In order to run a file directly, we’ll need to change the permissions to allow the script to be executable for the user. chmod is a command that changes permissions on a file, and +x will add execute rights to the script.
In order to interpret the file as an executable, you’ll also have to add the shebang ( #! ) at the top of the script. In Unix-like systems, a text file with a shebang is interpreted as an executable file. You can confirm where the bash interpreter is located with which bash.
We’ll add #!/bin/bash to the top of the script.
Note: You may also see #!/usr/bin/env bash instead, which can be used if you don’t know the exact path for bash.
Now you can run hello-world directly.
Note: In order to run a bash script without specifying the directory (using ./ , for example) you would have to add the directory of the script to the PATH by running export PATH=$PATH:/path/to/script/directory . However, this is generally not necessary for personal scripts.
A simple string in Bash does not require double quotes — you can write it directly.
echo Just a regular string
A single or double quote will expect a closing match, so in order to use one in such a string, you would need to escape the quote.
However, if you want to use a single or double quote in a string without escaping characters, you can do so by wrapping your string in quotes.
echo 'A single quoted "string"' echo "A double quoted 'string'"
A single quoted "string" A double quoted 'string'
With the -e flag, bash will interpret strings with backslash-escaped characters, such as \n for newline. This also requires a quoted string.
echo -e "This string has a \new line"
This string has a new line
Double quoted strings are also important for use with variables, as we’ll see in the next section.
A variable is declared without a dollar sign ( $ ), but has one when invoked. Let’s edit our hello-world example to use a variable for the entity being greeted, which is World .
#!/bin/bash who="World" echo "Hello, $who!"
Note that who = «World» with a space between the assignment is not valid — there must not be a space between variable and value.
Double quoted strings are required for interpolating variables. Within a single quoted string, the dollar sign would be interpreted literally
Another way you might see variables written is surrounded by curly brackets along with the dollar sign, which is known as parameter expansion.
This syntax is necessary for anything more complex you might do with a variable, such as getting one item from an array.
If you would like to use the output of a shell execution within a string, you can do so with a dollar sign followed by parentheses. ( $() ). For example the whoami command will print out your current user. To use it within a string, wrap whoami in the shell execution syntax.
We declared a variable in the last example, but we can also have the user set the value of a variable dynamically. For example, instead of just having the script say Hello, World! , we can make it ask for the name of the person calling the script, then output that name. We’ll do this using the read command.
#!/bin/bash echo 'Who are you?' read who echo "Hello, $who!"
Who are you? > Tania Hello, Tania!
Operators are slightly different in bash than what you might be used to.
In order to compare numbers, you will use the operators in the number comparison column, such as -lt for less than.
In order to compare strings, you will use the operators in the string comparison column, such as < for less than.
This is the opposite of what you might expect, but it’s the way it works in bash.
Number Comparison | String Comparison | Description |
---|---|---|
-eq | == | Equal |
-ne | != | Not equal |
-gt | > | Greater than |
-ge | >= | Greater than or equal |
-lt | Less than | |
-le | Less than or equal |
You can also use -z to test for emptiness on a string.
if statements use the if , then , else , and fi keywords. The condition goes in square brackets.
#!/bin/bash echo 'How old are you?' read age if [ $age -gt 20 ] then echo 'You can drink.' else echo 'You are too young to drink.' fi
How old are you? > 30 You can drink.
Bash uses for , while , and until loops. In this example, I’ll use the for. in loop to get all the files in a directory and list them.
#!/bin/bash files=/Users/you/dev/* for file in $files do echo $(basename $file) done
hello-world check-id list-files
An array in bash is defined inside parentheses. There are no commas between the items of the array.
beatles=('John' 'Paul' 'George' 'Ringo')
To access an item from an array, you’ll use square brackets ( [] ). Arrays are 0-indexed in bash. It is also necessary to use the paramter expansion syntax.
I hope this article has been helpful for you to get started with bash scripting. The concept of having a script that has complete access to anything on my computer was initially a frightening thought for me, but once I got accustomed to it I learned how useful and efficient it can be.
Newsletter
If you liked this post, sign up to get updates in your email when I write something new! No spam ever.
Comments
About me
Hello and thanks for visiting! My name is Tania Rascia, and this is my website and digital garden. 🌱
I’m a software developer who creates open-source projects and writes about code, design, and life. This site is and has always been free of ads, trackers, social media, affiliates, and sponsored posts.
Post Details
Category
Tags
Newsletter
Get updates when I write something new! No spam, I respect your inbox.
How to Create a Shell Script in Linux
Do you want to create a Shell script in your Linux system?
This guide will take you through how to create a shell script using multiple text editors, how to add comments, and how to use Shell variables.
But before heading over to creating a shell script, let’s understand what Shell scripting in Linux is.
What is Shell Scripting in Linux?
Shell Scripting is defined as an open-source program that’s run by Linux or Unix shell. Through shell scripting, you can write commands to be executed by the shell.
Lengthy and repetitive commands are usually combined into a simple command script. You can store this script and execute it whenever needed.
Shell scripting in Linux makes programming effortless.
Ways of Creating a Simple Shell Script in Linux
Creating a simple shell script in Linux is very easy. You can do that using multiple text editors. This tutorial will show how to create a shell script with two different methods, such as 1) using the default text editor, and 2) Using the Vim text editor tool.
Method 1: Using the Default Text Editor
To create a shell script using the default text editor, just follow the steps given below.
Step 1: Create a text file having a “.sh” extension. Then type a simple script.
Step 2: Now don’t change the directory. And open the terminal. Using the command below, give executable access to the file created.
Step 3: Execute the below-given script in the terminal:
This was a simple technique of creating a shell script in Linux using the default editor. Now, let’s look at the next method.
Method 2: Using the Vim Text Editor Tool
Vim text editor tool is a tool that helps create a shell script in a Linux system. In case you don’t have it already installed, use the command to install Vim:
Now follow the steps for creating a shell script using the tool.
Step 1: For opening the editor, simply type:
Step 2: Once you’re in, open the terminal. Then create a bash file via:
After the execution of the command, the editor will appear as below.
Step 3: Press “i” from the keyboard and get into the Insert mode. Now, type the following commands in it.
#! /bin/bash echo “Welcome to the Linux family.”
Step 4: Press “Esc” to exit this mode. Then type “:w” to save your script.
Once saved, the shell script will appear as below.
Step 5: When you’re back to the console, type “:q”. Then write:
The above command will execute the shell file and will display the output in the terminal.
Adding Comments in Shell
Just like in many other programming languages, we use “#” (the hashtag symbol) to add comments in the shell script.
In the Vim editor, open the text file. And write a comment as below.
#! /bin/bash # This is the testing script! echo “Welcome to the Linux family.”
The above example illustrates the usage of the “#” symbol in adding comments in a shell script.
Using Shell Variables
Variables are a value that can store information in the form of numbers and characters. Likewise, Shell variables can store data as well. For example,
The above lines will create a shell variable “var” and then will print it.
Let’s write a small script, now.
#! /bin/bash variable=“This is the testing shell script.” echo $variable
To get the value of the variable, execute the command below.
Let’s write another script using a variable.
#!/bin/sh echo "what is your name?" read name echo "How do you do, $name?" read remark echo "I am $remark too!"
Run the script file and enter the “name” as “Robin”.
bash scriptsample.sh what is your name? Robin
As you enter the input, the script reads the name and replies:
Then enter the “remark” as “good”. And you’ll notice that the script repeats the remark.
The second line of the above set of codes shows the response from the script.
These were some simple shell scripts. You can write advanced scripts containing loops, functions, and conditional statements. Shell scripting will make Linux administration a breeze.
The Conclusion
In this article, you have learned to create a simple Shell script. Now you can create your own scripts in Linux following the above-mentioned methods and tips.
Suparna is a freelance writer who writes about Linux including tips, tricks, and how-tos.