Running a Bash Script in Different Ways

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 28 of 205

A Bash script can be started in several ways, and they are not interchangeable. Some run the script in a new process that cannot change your shell, some run it inside your current shell, and some choose a different interpreter than the one named in the file. Knowing the differences explains many puzzling situations, such as a script that changes directory but leaves you where you were, or one that closes your terminal when it ends. This lesson uses a small script to compare every common method.

Understanding the Concept

Whenever you run a script, there are two questions to answer:

  1. Which interpreter reads the file? Bash, sh, or another program.
  2. In which process does it run? In a new child process, or in your current shell.

The second question matters most. A child process gets its own copy of the environment, so anything it changes (variables, the current directory) disappears when it ends. A script run in the current shell can change your shell, and the changes stay.

The Sample Script

Save this as info.sh in a practice directory. It prints details about itself, then sets a variable and changes directory:

#!/usr/bin/env bash
echo "script name : $0"
echo "process id  : $$"
echo "directory   : $(basename "$PWD")"
greeting="Hello from info.sh"
cd /

Make it executable with chmod +x info.sh. The special variable $0 is the name used to start the script, and $$ is the process ID of the shell that is running it. The last two lines set a variable and move to the root directory. They are there to show whether the changes survive.

Method 1: Pass the Script to bash

bash info.sh

Output (the process ID and directory name vary):

script name : info.sh
process id  : 4821
directory   : lessons

You started a new bash program and gave it the file as an argument. The shebang is ignored, because the file is data for the program you chose, and the line is only a comment. The file needs the read permission, but not the execute permission. This is the safest method to try a script you have just received.

Method 2: Run the File Directly

./info.sh

Output:

script name : ./info.sh
process id  : 4830
directory   : lessons

Here the system uses the shebang to pick the interpreter, as the shebang lesson explained. The file needs both the read and the execute permissions. The leading ./ is required because the current directory is not part of PATH. Note that $0 now holds ./info.sh, the path you typed.

You can also give a full path or a path relative to another directory:

/home/suriya/lessons/info.sh
../lessons/info.sh

Any command containing a slash is run from exactly that location, with no search.

Method 3: Put the Script in PATH

If you place a script in a directory listed in PATH and give it execute permission, you can run it by name alone, from any directory. This creates a small bin directory and adds it to PATH for one command:

mkdir -p bin
cp info.sh bin/info
PATH="$PWD/bin:$PATH" info

Output:

script name : /home/suriya/lessons/bin/info
process id  : 4838
directory   : lessons

Because Bash found the script by searching PATH, $0 is the full path where it was found. Notice that the copy has no .sh extension. Users of a command do not need to know the language it is written in, so system commands usually have no extension. To make the change permanent, add the directory to PATH in your startup file; a later lesson on startup files explains how.

Method 4: Run It with sh

sh info.sh

This starts the program named sh, which is not always Bash. On Debian and Ubuntu, sh is Dash, a smaller shell. You can check:

ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Mar 31  2024 /bin/sh -> dash

Our sample script runs under Dash because it uses only simple commands. A script that uses Bash features, such as [[ ... ]], arrays or ${var^^}, would fail. Use bash, not sh, for Bash scripts.

Method 5: Feed the Script Through Standard Input

A shell reads commands from its standard input when it has no file to run. This lets you pipe or redirect a script into it:

bash < info.sh

Output:

script name : bash
process id  : 4846
directory   : lessons

The name is bash, because there is no script file; the commands came from the input stream. You can pass arguments to a script read from input with the -s option and --:

echo 'echo "got: $1"' | bash -s -- hello
got: hello

The -s option means "read commands from standard input", and everything after -- becomes $1, $2 and so on.

Method 6: Run a String with bash -c

For a one-line command, the -c option takes the commands as a string:

bash -c 'echo "one-liner: $((6*7))"'
one-liner: 42

The string is single-quoted so that the outer shell does not expand $((6*7)); the new bash does it. This form is how other programs, such as cron and ssh, hand a command to Bash.

Method 7: Run in the Current Shell with source or .

The previous methods all start a new process. The source command, and its shorter form, a single dot (.), do something different: they read the file and execute its lines inside your current shell.

source ./info.sh
. ./info.sh

The two lines are equivalent. The dot form is the older, POSIX name, and source is a Bash synonym. The file needs only the read permission, and the shebang line is just a comment.

The ./ in these examples only makes the location explicit. When the name has no slash, source searches the directories in PATH first and then, in Bash's default mode, the current directory, so source info.sh also finds the file in the current directory.

To see the difference clearly, run it first as a child process, and then in the current shell, checking the state of the shell after each:

./info.sh > /dev/null
echo "${greeting:-unset}"
pwd
unset
/home/suriya/lessons

The child process set greeting and changed to /, but those changes vanished with the process. The parent shell still has no greeting and has not moved. Now with source:

source ./info.sh > /dev/null
echo "${greeting:-unset}"
pwd
Hello from info.sh
/

This time both changes stayed. The shell that is running the script is your own shell, so setting a variable and calling cd changed it. That is exactly why startup files such as .bashrc and scripts that set up an environment (for example, a Python virtual environment's activate file) must be sourced and not executed: their whole purpose is to change your current shell.

The Process ID Proves It

A script printing its own process ID shows whether it runs in a new process. Save this as pid.sh:

#!/usr/bin/env bash
echo "script pid=$$ parent=$PPID"

Run it from a shell whose own ID is printed first:

echo "shell pid=$$"
./pid.sh
source ./pid.sh
shell pid=384
script pid=385 parent=384
script pid=384 parent=348

The executed script got its own process ID (385), and its parent is the shell (384). The sourced script reports the same ID as the shell (384), because it is the shell. ($$ in a script always shows the ID of the main shell process, and $PPID is the parent of that process.)

Arguments with source

A sourced file can receive arguments, which become its positional parameters while it runs:

printf 'echo "args: $# -> $1 $2"\n' > args.sh
source ./args.sh red blue
args: 2 -> red blue

exit and return in a Sourced File

Because a sourced file runs in your shell, the exit command in it exits your shell. In an interactive terminal this closes the terminal window or ends the session. To see this without risk, the test below uses a throwaway bash -c shell:

printf 'echo "about to exit"\nexit 3\n' > quit.sh
bash -c 'source ./quit.sh; echo "this line never runs"'
echo "status=$?"
about to exit
status=3

The line after source never ran, because the shell that was executing it ended. A script meant to be sourced should use return, which stops only the sourced file and gives control back to the caller:

printf 'echo "start"\nreturn 0\necho "never"\n' > ret.sh
bash -c 'source ./ret.sh; echo "back in caller, status=$?"'
start
back in caller, status=0

If the same exit 3 file is executed with ./quit.sh (after chmod +x quit.sh), only the child process ends, and the parent continues and reads the status:

./quit.sh; echo "child finished with $?"
about to exit
child finished with 3

source Needs a Real File

If the file does not exist, source reports an error and returns status 1:

bash: nosuch.sh: No such file or directory

Method 8: Replace the Shell with exec

The exec built-in replaces the current process with another program instead of starting a child. Nothing after it in the script runs:

#!/usr/bin/env bash
echo "wrapper start"
exec echo "replaced by echo"
echo "never printed"
wrapper start
replaced by echo

Use exec in a launcher script that only prepares an environment and then hands over to the real program.

Comparing the Methods

MethodInterpreter chosen byNew processChanges the current shellNeeds x permission
bash script.shYouYesNoNo
./script.shThe shebangYesNoYes
script (found in PATH)The shebangYesNoYes
sh script.shYou (sh)YesNoNo
bash < script.shYouYesNoNo
source script.sh / . script.shYour current shellNoYesNo

All of these need the read permission on the file.

What Happens When You Forget the ./

If you type only the name, Bash searches PATH and does not find the file:

info.sh
bash: info.sh: command not found

The exit status is 127. Write ./info.sh or the full path.

Practical Applications

Trying a script safely. Run an unfamiliar script with bash script.sh first. It needs no permission change, and a mistake affects only a child process.

Loading settings. Keep project settings in a file such as settings.sh, for example export API_URL="https://api.example.com", and load them with source settings.sh. The variables are then available to every command that follows in the same shell.

Reusing functions. A file that defines functions can be sourced from many scripts. Because the functions are defined in the current shell, the caller can use them afterward. A later lesson on sourcing other Bash files covers this in depth.

Running by cron or ssh. Programs that start commands for you usually go through bash -c or call the script by full path. Always give the full path in such cases, because those environments have a smaller PATH than your terminal.

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 Running a Bash Script in Different Ways and get answers drawn from it.

Signed-in readers only.