Operations 4 min read

How to Create and Run Executable Bash Scripts on Linux

This guide walks you through creating a .sh Bash script, adding a simple “Hello World” program, granting execute permission with chmod, and running it directly or via sh/bash, plus a practical backup script example that archives /var/log using tar.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Create and Run Executable Bash Scripts on Linux

Creating a Bash script file

Create a new file with the .sh extension using the touch command.

touch hello_script.sh

Writing the script

Open the file with vim (or any editor) and insert a shebang line followed by a simple command, for example:

#!/bin/bash
echo "Hello World"

Save the file and exit the editor.

Running the script

There are two ways to execute the script. The first uses the sh or bash interpreter explicitly:

sh hello_script.sh
bash hello_script.sh

Both commands output Hello World.

Setting execute permission

Make the script directly runnable by adding the executable flag with chmod:

chmod +x hello_script.sh

Running the script directly

After the permission is set, run the script without specifying the interpreter:

./hello_script.sh

Backup script example

A more practical example creates a backup script that archives /var/log into a timestamped tar.gz file.

#!/bin/bash
TIME=`date +%Y_%m_%d`
DESTINATION=/tmp/backup-$TIME.tar.gz
SOURCE=/var/log
tar -zcvf $DESTINATION $SOURCE

Give the script execute permission and run it:

chmod +x backup_script.sh
./backup_script.sh

The command produces a compressed backup file in /tmp named with the current date.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BashShell scriptingchmodBackup Scriptexecutable permission
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.