Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Create a Bash Script, Step by Step

Write your first Bash script, make it executable and run it.

VPS and Cloud Servers2 min read4 steps6 screenshots

What a Bash script is

A Bash script is a text file with commands that run one after another. Use scripts to automate jobs you repeat, such as backups and updates.

Step 1: Pick an editor

You can use any text editor. nano is easy for beginners and vim is more powerful. Install them if needed:

sudo apt install nano
sudo apt install vim

Step 2: Write the script

Create the file. The extension .sh is a habit and not a must:

nano bash_script.sh

The first line is the shebang. It tells the system which program runs the file:

#!/bin/bash
The shebang line

Add your commands below it:

#!/bin/bash
echo "Hello, World!"

Save and close the file.

Step 3: Make it executable

chmod +x bash_script.sh
Making the script executable

Step 4: Run it

./bash_script.sh

You can also start it with bash and no execute right:

bash bash_script.sh

Step 5: Test and debug

Test the script on a copy of your data first. To see each command as it runs, start it in debug mode:

bash -x bash_script.sh

A full example

  1. Create the file:
nano bash_script.sh
Opening the file in nano
  1. Write this:
#!/bin/bash
# Store a number in a variable
number=10
# Print the number
echo "The number is: $number"
The script in the editor
  1. Give execute rights to all users (use chmod +x if you only need yourself):
chmod a+x bash_script.sh
Setting the permissions
  1. Run it with either command:
./bash_script.sh
bash bash_script.sh
The script output

Bash basics

  • Comments start with #.
  • Variables are set without spaces: name="Hostvento", and used with $name.
  • Conditions: if [ "$a" -gt 5 ]; then ... fi
  • Loops: for i in 1 2 3; do echo $i; done
  • Input: read answer waits for the user.
  • Exit codes: exit 0 means success.

Quick recap

  • Start with #!/bin/bash.
  • Make the file executable with chmod +x.
  • Run it with ./script.sh, and debug with bash -x.