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.
Creating a Bash script file
Create a new file with the .sh extension using the touch command.
touch hello_script.shWriting 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.shBoth commands output Hello World.
Setting execute permission
Make the script directly runnable by adding the executable flag with chmod:
chmod +x hello_script.shRunning the script directly
After the permission is set, run the script without specifying the interpreter:
./hello_script.shBackup 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 $SOURCEGive the script execute permission and run it:
chmod +x backup_script.sh
./backup_script.shThe command produces a compressed backup file in /tmp named with the current date.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
