Bash Script Example for Beginners

Bash Script Example – In this Bash Tutorial, we shall look into an example Bash script file, understand what each part of the script does, and learn how to run it in a Bash shell.

A Bash script is a plain text file that contains shell commands written in the order in which they should be executed. Instead of typing the same commands repeatedly in the terminal, you can save them in a script file and run the file whenever required.

What a Bash Script File Contains

  1. A Bash Script file is a program that contains bash commands to be executed in sequence.
  2. For a file to be a bash script file, either the extension of it should be sh or the first line in the file should be #!/bin/bash. Look into Bash Extension for further details.
  3. For the bash script file to be executed, the user should have permissions to execute the script.
  4. If a command fails to get executed due to an error in its syntax or a run-time error, the execution is stopped there, and no further commands are executed.
  5. Bash Script file can have comments in between commands for improving the understandability.
  6. Bash Scripting, like other programming languages, has conditional statements, looping statements and many other commands which we shall learn in detail in due course of this tutorial.

One important correction for new learners: by default, Bash does not always stop a script just because one command returns a non-zero exit status. If you want a script to stop on many command failures, you can use options such as set -e, but that behavior should be used carefully after understanding how exit statuses work.

Bash Script Shebang, Comments, Commands, and Variables

A typical Bash script contains a shebang line, commands, optional comments, variables, loops, and conditional statements. The shebang line tells the operating system which interpreter should run the file when it is executed directly.

Part of Bash scriptExamplePurpose
Shebang#!/bin/bashSpecifies Bash as the command interpreter.
Comment# this is a commentDocuments the script and is ignored during execution.
Commandecho HelloRuns a shell command.
Variablename="Alex"Stores a value for later use.
Loopfor item in ...Repeats commands for multiple values.

The conventional shebang format is shown below. Some systems also use #!/usr/bin/env bash when Bash may be installed in different locations.

</>
Copy
#!/bin/bash

Example Bash Script File That Lists Directory Contents

Following is an example bash script file.

Bash Script File

</>
Copy
#! /bin/bash

echo Welcome to learn Bash Scripting.

echo For an example we shall list files in the current directory

# this is a comment and ignored while execution

i=0
array=()
while read -r line
do
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -lt)

for fn in "${array[@]}"
do
    echo $fn
done

This script prints two messages, reads the output of ls -lt line by line, stores each line in an array, and then prints every array element. The while read -r line loop reads each line safely without treating backslashes as escape characters. The for fn in "${array[@]}" loop then prints each stored line.

How to Save and Run a Bash Script File

Save the script in a file, for example bash-example or bash-example.sh. The .sh extension is common and useful for readability, but the execute permission and shebang are what allow the file to be run directly as a script.

Give the script execute permission using chmod.

</>
Copy
chmod +x bash-example

Then run the script from the current directory using ./ before the file name.

</>
Copy
./bash-example

The ./ prefix tells the shell to run the executable file from the current directory. Without it, Bash searches only the directories listed in the PATH environment variable.

Bash Script File Permissions Before Execution

File permissions

~/workspace/bash$ ls -l bash-example
-rwxrwxrwx 1 tutorialkart tutorialkart 312 Dec  5 10:02 bash-example

Please observe that the file has permissions to be executed at user, group and administrator levels. You may modify those permissions according to your need using ‘chmod’ command.

The permission string -rwxrwxrwx means that the owner, group, and others all have read, write, and execute permissions. In regular usage, you usually do not need to give everyone write access. A common safer permission for a personal script is owner read-write-execute and group/others read-execute, such as 755.

</>
Copy
chmod 755 bash-example

Output of the Bash Script Example

To execute the Bash Script File, you may open a terminal in Ubuntu or Mac OS (which by default runs bash shell) or Bash Program in Windows, and execute the file as shown below (with ./ preceding the file name) :

~/workspace/bash$ ./bash-example 
Welcome to learn Bash Scripting.
For an example we shall list files in the current directory
total 168
-rwxrwxrwx 1 arjun arjun 312 Dec 5 10:02 bash-example
-rwxrwxrwx 1 arjun arjun 65 Dec 4 17:07 bash-substring-example
drwxrwxr-x 2 arjun arjun 4096 Dec 4 12:50 file

The exact output will be different on your computer because ls -lt lists files from your current directory. The first two lines come from the echo commands in the script, and the remaining lines come from the directory listing.

Small Bash Script Example with a Variable and Condition

The next example is shorter and shows a common beginner pattern: read a value, store it in a variable, and use an if condition.

</>
Copy
#!/bin/bash

name="TutorialKart"

if [ -n "$name" ]; then
    echo "Hello, $name"
else
    echo "Name is empty"
fi

In this example, [ -n "$name" ] checks whether the variable contains a non-empty string. The double quotes around $name help avoid unexpected behavior when the value contains spaces or is empty.

Common Mistakes When Running a Bash Script

  • Permission denied: Run chmod +x script-name before executing the file directly.
  • Command not found: Use ./script-name when running a script from the current directory.
  • Bad interpreter: Check the shebang line and make sure the Bash path is valid.
  • Windows line endings: If a script created on Windows fails on Linux, convert CRLF line endings to LF.
  • Unquoted variables: Quote variables such as "$file" when values may contain spaces.

Bash Script Example Editorial QA Checklist

  • Confirm that the Bash script has a valid shebang line such as #!/bin/bash.
  • Verify that every command shown in the script is explained in beginner-friendly terms.
  • Check whether command blocks use language-bash and output-only blocks are clearly separated.
  • Ensure the tutorial explains execute permission and the need for ./ when running a local script.
  • Confirm that the article does not incorrectly state that Bash always stops after any failed command.
  • Test the sample script in a Bash shell before publishing changes.

Bash Script Example FAQs

What is a Bash script example?

A Bash script example is a text file that contains Bash commands such as echo, ls, loops, variables, and conditions. When the file is executed, Bash runs those commands in order.

How do I run a Bash script from the terminal?

Save the script file, give it execute permission using chmod +x file-name, and run it with ./file-name from the directory where the file is saved. You can also run it with bash file-name without making it executable.

Does a Bash script file need the .sh extension?

No. The .sh extension is helpful for readability, but it is not required. A script can run without the extension if it has a valid shebang and execute permission, or if it is passed directly to Bash.

Why do we use chmod before running a Bash script?

chmod is used to add execute permission to the script file. Without execute permission, the operating system may return a permission denied error when you try to run the script directly.

Is Bash or Python easier for scripting?

Bash is usually simpler for combining shell commands, file operations, and automation in a terminal. Python is often easier for larger programs, complex data processing, and scripts that need clearer structure across platforms.

Conclusion: Running Your First Bash Script

In this Bash Tutorial, we have written a Bash Script and learnt about the file permissions that it should have, to execute it.

You also learned how the shebang line, comments, variables, loops, execute permission, and the ./ prefix work together when running a Bash script. With these basics, you can start creating small scripts to automate repeated terminal commands.