My Computer Tips

Home | About | Categories | All Tips & Tutorials

Create a simple bash script in Ubuntu and Ubuntu based distributions

ID: 53

Category: Bash Scripts

Added: 18th of December 2015

Updated On: Tutorial updated and rechecked on 8th of November 2024

Views: 4,581

Bash scripts allow to automate tasks in Ubuntu. A good example of using a bash script could be to install a bunch of packages after reinstalling Ubuntu or resizing a bunch of images.

To create your first bash script in Ubuntu follow the instructions below.

We first need to identify the path to bash, so open your terminal and enter the following command

which bash

It will return with /usr/bin/bash, this is what you will enter at the top of every new bash script you create.

Create a new text document and copy and paste the code below.
#!/usr/bin/bash
echo "My First Bash Script"

Save the text document as my_first_bash_script.sh to your desktop so you can easily locate it.

Before we can run the bash script we need to make it executable. Open your terminal and change directory to your desktop using the following command
cd /home/{username}/Desktop

Remember to replace {username} with your Ubuntu username

Make the file executable my issuing the following command. What this command does is give you read and write permissions on the file.
chmod +x my_first_bash_script.sh

The next part is to run the bash script. In the terminal enter the following command
./my_first_bash_script.sh

Another way to run your bash script would be to create a shortcut (Symbolic Link) to it, so you don't need to access the terminal.