Creating Your First Bash Script

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 25 of 205

Typing commands one at a time is fine for a quick task, but the moment you want to repeat a task, you need a script. A script is a plain text file of commands. Instead of retyping them, you save them once and run the file whenever you need them. In this lesson you will create two small scripts, run them in more than one way, and learn what each of the common error messages means.

Understanding the Concept

A Bash script is nothing special. It is an ordinary text file, and Bash reads it from top to bottom, running each line as if you had typed it at the prompt. Three things turn a text file into a script that is convenient to run:

  1. The first line says which program should run the file (the shebang line).
  2. The file has permission to be executed.
  3. You tell Bash where the file is.

You will meet all three in this lesson. The file name usually ends in .sh, but this is a habit and not a rule: Bash does not care about the extension. The extension helps people and editors recognize the file.

Writing the Script

Any text editor can create a script: nano in the terminal, or Visual Studio Code, Vim and so on. You can also create the file from the shell with the cat command and a here document. That technique is explained in a later lesson, so for now think of it as a way to save the lines you type into a file:

cat > hello.sh <<'EOF'
#!/usr/bin/env bash
echo "Hello, Bash!"
EOF

Everything between <<'EOF' and the closing EOF line is written into hello.sh. The file now holds two lines:

#!/usr/bin/env bash
echo "Hello, Bash!"

The first line is the shebang, which tells the system to run the file with Bash. The second line is a command that prints a message. To see the file, run cat hello.sh.

Running a Script with the bash Command

The simplest way to run a script is to give it to bash as an argument:

bash hello.sh

Output:

Hello, Bash!

This works immediately because you are not running the file itself; you are running bash and asking it to read the file. It needs no special permission other than the right to read the file.

Running a Script Directly

The other way is to run the file as if it were a program. Try it now:

./hello.sh
echo "status=$?"

Output:

bash: ./hello.sh: Permission denied
status=126

The file is not allowed to be executed yet. New files are created without the execute permission, a safety measure that prevents a downloaded or newly created file from running by accident. The exit status 126 means "found, but cannot be executed".

The chmod command changes permissions. The option +x adds execute permission:

chmod +x hello.sh
./hello.sh
echo "status=$?"

Output:

Hello, Bash!
status=0

The next lessons explain permissions and chmod in detail. The stat command can confirm the result: the first column shows x for execute.

stat -c '%A %n' hello.sh

Output:

-rwxr-xr-x hello.sh

The characters after the first dash are three groups of rwx for the owner, the group and everyone else. The x in each group means that all three may execute the file.

Why You Need the ./ Prefix

You may wonder why you must type ./hello.sh and cannot just write hello.sh. Try it:

hello.sh

Output:

bash: hello.sh: command not found

When you type a name with no slash in it, Bash searches only the directories listed in the PATH variable, and the current directory is deliberately not part of that list. Writing ./hello.sh gives a path, and a command that contains a slash is run from exactly that location, with no search. The leading ./ means "the current directory". The exit status for a command that cannot be found is 127.

A Script That Uses Variables and Arguments

A script becomes more useful when it can change its behavior. This second script greets a person by name, and it takes the name from the command line:

#!/usr/bin/env bash
# greet.sh - greet a person by name.
name=${1:-World}
today=$(date +%A)
echo "Hello, $name!"
echo "Today is $today."

After saving it as greet.sh and making it executable with chmod +x greet.sh, run it with a name:

./greet.sh Suriya

Output (the weekday is the day when you run it):

Hello, Suriya!
Today is Friday.

Run it with no name, and the default value takes over:

./greet.sh

Output:

Hello, World!
Today is Friday.

Understanding the Script

  • The line starting with # after the shebang is a comment. Bash ignores it.
  • $1 is the first argument given on the command line. When you run ./greet.sh Suriya, $1 is Suriya.
  • ${1:-World} means "use $1, but if it is missing or empty, use World instead". This is called a default value. The later lessons on variables and parameter expansion explain it fully.
  • name=... creates a variable. There must be no spaces around the equals sign.
  • $(date +%A) runs the date command, and %A makes it print the weekday name. The output replaces the $(...) text, so today holds a word such as Friday.
  • Each echo prints a line. The double quotes keep the variable's value together and allow $name and $today to be replaced by their values.

The script ends after its last command, and its exit status is the status of that last command:

./greet.sh > /dev/null
echo "status=$?"

Output:

status=0

Redirecting the output to /dev/null discards it, so only the status line appears.

When a Script Does Not Run

Most first-script problems come from a small set of causes, and each one gives a recognizable message.

What you seeWhat it means
Permission deniedThe file lacks execute permission. Run chmod +x file.
command not foundBash did not find the file. Use ./file, or the full path.
/usr/bin/env: 'bash\r': No such file or directoryThe file uses Windows line endings.
bash: ./file: cannot execute: required file not foundThe shebang line gives a path to a program that does not exist.
/usr/bin/env: 'name': No such file or directoryThe shebang uses env, but the named program is not installed.

The third message deserves an explanation. Windows editors end each line with two characters, a carriage return and a line feed (\r\n), while Linux and macOS use only the line feed. If a script was saved with Windows line endings, the shebang becomes #!/usr/bin/env bash followed by an invisible carriage return, and the system looks for a program literally called bash\r:

/usr/bin/env: 'bash\r': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines

The exit status in this case is 127. The fix is to save the file again with Unix (LF) line endings. Most editors have this setting in the status bar, and the dos2unix tool converts a file when it is installed.

What Happens Without a Shebang

If the first line is missing, the file can still run. In an interactive Bash session, a file with no shebang is run by Bash itself:

printf 'echo "no shebang"\n' > ns.sh
chmod +x ns.sh
./ns.sh

Output:

no shebang

This is convenient but unreliable. Which shell runs the file depends on the program that starts it, and a script that relies on Bash features may fail under another shell. Always write the shebang line so that the script behaves the same everywhere.

Practical Applications

A script is the right tool whenever you would otherwise repeat the same commands. Here is a small script that prepares a project folder with a standard set of directories. Save it as new_project.sh:

#!/usr/bin/env bash
# new_project.sh - create a project folder with a standard layout.
project=${1:-my-project}
mkdir -p "$project"/src "$project"/docs "$project"/tests
echo "Created $project"

Run it after chmod +x new_project.sh:

./new_project.sh blog

Output:

Created blog

The folder blog now contains src, docs and tests. The -p option of mkdir creates the parent folder and does not complain if a folder already exists, so the script can be run twice without an error.

To run a script from any directory without typing its path, place it in a directory that is listed in PATH, such as ~/bin on many systems, and make it executable. The later lessons on environment variables show how to check and change PATH.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Creating Your First Bash Script and get answers drawn from it.

Signed-in readers only.