DEV Community

Cover image for How to Use Bash to Write a Simple Script
jones268
jones268

Posted on

How to Use Bash to Write a Simple Script

Bash is a Unix shell used in Linux and MacOS. We will be using a bash script to make a program that runs in the background.

You need to know how to open a terminal in your operating system. On Ubuntu, you can press Ctrl+Alt+t . On Mac, you can press Command+Space, then type Terminal and press Enter.

To make bash scripts, you should know Linux commands. To practice the command line, you can use this site

What is a bash script?

A Bash script is a text file containing a series of Bash commands. When the file is executed, the commands are executed in sequence as they appear in the text file.

To get started, you can create a new script called my_script.sh.

A simple script would be:

echo "Hello World"
Enter fullscreen mode Exit fullscreen mode

Make it executable with the command:

chmod +x my_script.sh
Enter fullscreen mode Exit fullscreen mode

This script will run when you enter the following command:

./my_script.sh
Enter fullscreen mode Exit fullscreen mode

You can always stop the script by pressing Ctrl+C.

Any bash command can be inside your bash script. Besides commands, the scripting language also supports for loops and if statements. Variables can be used too.

Variables

A bash variable is a variable, that stores string values.

For example the following code prints the contents of the variable "friend"

echo $friend
Enter fullscreen mode Exit fullscreen mode

To change the value of a bash variable we use the '=' (or the s equal operator).

For example, to change the value of "user" to "john" we write: user="john"

user="john"
echo $user
Enter fullscreen mode Exit fullscreen mode

If statements

If statements are a simple tool for logic in bash. If statements can be used in bash.

The syntax is:

if [ -z "$1" ]; then
fi
Enter fullscreen mode Exit fullscreen mode

For example, if your script should only execute the echo hello world command if the script was run on a Mac, you could use the following syntax:

if [[ $OSTYPE == *"Mac OS X"* ]]; then
echo hello world
fi
Enter fullscreen mode Exit fullscreen mode

For loops

This lets you repeat code. See the following code:

#!/usr/bin/env bash
for i in {1..10}; do
echo "hello, world $i"
done
Enter fullscreen mode Exit fullscreen mode

If you run this program, then it will produce the following output:

$ ./my_script_with_for.sh
hello, world 1
hello, world 2
hello, world 3
hello, world 4
hello, world 5
hello, world 6
hello, world 7
hello, world 8
hello, world 9
hello, world 10
Enter fullscreen mode Exit fullscreen mode

By using the “for” command, you can do something in a loop.

Top comments (0)