How To Run A Sh File In Terminal

8 min read

Running a shell script (a file ending in .Whether you are a developer automating a build process, a system administrator managing servers, or a student learning the command line, understanding how to execute these files safely and effectively saves hours of manual work. sh) is a fundamental skill for anyone working in a Linux, macOS, or Unix-like environment. This guide covers every standard method, explains the underlying permissions system, troubleshoots common errors, and outlines security best practices so you can run scripts with confidence Small thing, real impact..

This is the bit that actually matters in practice.

Understanding What a .sh File Actually Is

Before typing any commands, it helps to know what you are executing. That's why a file with the . Because of that, sh extension is simply a text file containing a sequence of commands that you could otherwise type manually into the terminal. The "sh" stands for Shell, typically referring to the Bourne Shell or its modern compatible replacements like Bash (Bourne Again Shell), Zsh, or Dash But it adds up..

The very first line of a well-written script usually looks like this:

#!/bin/bash

This line is called the shebang (or hashbang). It tells the operating system exactly which interpreter should parse the rest of the file. Here's the thing — while . sh is the conventional extension, Linux does not strictly require extensions to execute files; the permissions and the shebang are what truly matter.

The Two Main Approaches to Execution

Two distinct ways exist — each with its own place. Choosing the right one depends on whether you have modified the file's permissions and how you prefer to manage your environment.

Method 1: Explicitly Calling the Interpreter (No Permission Change Required)

This is the quickest way to run a script if you do not want to modify file permissions or if you are testing a script downloaded from an untrusted source. You explicitly tell the shell interpreter (like bash or sh) to read and execute the file.

Open your terminal, manage to the directory containing the script using cd, and run:

bash script_name.sh

Or, if the script is written strictly for the POSIX standard shell:

sh script_name.sh

Why use this method?

  • Safety: The file does not need "execute" permissions. This prevents accidental double-click execution in a file manager.
  • Portability: You can force a specific interpreter (e.g., running a Bash script with bash even if your default shell is Zsh).
  • Debugging: You can easily pass flags to the interpreter, such as bash -x script_name.sh to enable debug mode (printing every command before execution).

Method 2: Making the File Executable (The Standard Unix Way)

This is the traditional, "native" way to run programs in Unix-like systems. So you change the file's mode bits to mark it as an executable program. Once done, you run it by referencing its path directly And that's really what it comes down to..

Step 1: Grant Execute Permissions Use the chmod (change mode) command. The +x flag adds execute permission for the user, group, and others.

chmod +x script_name.sh

Advanced Tip: For better security on multi-user systems, restrict execution to only the file owner:

chmod u+x script_name.sh

Step 2: Run the Script Now you execute it by providing the relative or absolute path. Because the current directory (.) is usually not in the system $PATH variable for security reasons, you must prefix the filename with ./

./script_name.sh

Why the ./ prefix? Unlike Windows, Linux does not automatically look in the current folder for executables. This prevents a malicious script named ls or cd in a downloaded folder from hijacking your standard commands. The ./ explicitly says "look right here, in the current directory."

Passing Arguments to Your Script

Scripts become powerful when they accept input. You pass arguments after the script name, separated by spaces.

./backup_script.sh /home/user/documents /mnt/backup_drive

Inside the script, these arguments are accessed via positional parameters:

  • $0: The name of the script itself. Day to day, : The first, second, third arguments. Worth adding: * $@: All arguments as a list. * $1, $2, $3...* $#: The total count of arguments.

Example usage inside backup_script.sh:

#!/bin/bash
SOURCE_DIR=$1
DEST_DIR=$2

echo "Backing up $SOURCE_DIR to $DEST_DIR..."
rsync -av "$SOURCE_DIR/" "$DEST_DIR/"

Troubleshooting Common Errors

Even with the correct commands, things go wrong. Here are the most frequent issues and how to fix them It's one of those things that adds up..

1. "Permission denied"

Cause: You tried ./script_name.sh but forgot chmod +x. Fix: Run chmod +x script_name.sh and try again. Alternative Cause: The filesystem is mounted with the noexec flag (common on /tmp or external NTFS/FAT32 drives). Fix: Move the script to your home directory or a standard Linux partition (ext4, xfs, btrfs) and run it there. Or use Method 1: bash script_name.sh Surprisingly effective..

2. "Command not found" (when using ./script_name.sh)

Cause: You are not in the directory where the file lives, or you misspelled the filename. Fix: Use ls to verify the file exists and check spelling. Use tab completion (type ./scr then press Tab) to avoid typos.

3. "Bad interpreter: No such file or directory"

Cause: The shebang line (#!/bin/bash) points to a path that doesn't exist on your system, or the file has Windows-style line endings (CRLF). Fix for Path: Check where bash actually lives: which bash. Update the shebang to match (usually #!/usr/bin/env bash is more portable). Fix for Line Endings: This happens often when editing files on Windows (VS Code, Notepad++) and moving to Linux. Convert the file:

sed -i 's/\r$//' script_name.sh
# OR use the dedicated tool if installed:
dos2unix script_name.sh

4. Script runs but does nothing / exits instantly

Cause: Logic errors, missing dependencies, or the script is sourcing variables instead of executing. Fix: Run with debug mode to trace execution:

bash -x script_name.sh

This prints every command and its expanded arguments to stdout, revealing exactly where the flow stops Worth knowing..

Running Scripts in the Current Shell Context: source vs. Execute

This is a critical distinction that confuses many beginners.

Standard Execution (./script.sh or bash script.sh)

This spawns a subshell (a child process) Small thing, real impact..

  • The script inherits a copy of your environment variables.
  • Any changes the script makes (changing directories cd, setting variables MY_VAR=foo, defining functions) die when the script finishes.
  • Your current terminal session remains untouched.

Sourcing (. script.sh or source script.sh)

This runs the commands inside your current shell process. No subshell is created.

  • Changes to environment variables, aliases, functions, and the current working directory persist after the script finishes.
  • This is how configuration files like .bashrc, .zshrc, or virtual environment activators (source venv/bin/activate) work.

Syntax:

source ./script_name.sh
# OR the POSIX shorthand (dot space filename)
. ./script_name.sh

Use sourcing only when you explicitly want the script to modify your current shell environment.

5. "Permission Denied" (when using ./script_name.sh)

Cause: The script lacks execute permission. Linux requires explicit permission to run a file as a program. Fix: Grant execute permission using chmod:

chmod +x script_name.sh

You only need to do this once. Afterward, ./script_name.sh will work. If you're the file owner and still get this error, double-check that you are in the correct directory.

6. Infinite Loops or Unexpected Behavior

Cause: A loop condition never becomes false, or logic doesn't account for all cases. Fix: Always use bash -x for debugging (as mentioned in point 4). For loops, ensure the variable changes in a way that will eventually meet the exit condition. For while loops, be cautious with conditions like while true unless you have a clear break statement.

Practical Example: Sourcing vs. Executing

Let's solidify the concept with a concrete example. Create a file named set_env.sh with the following content:

#!

**Scenario 1: Executing the Script**
```bash
# Make it executable first
chmod +x set_env.sh

# Run it
./set_env.sh
# Output: Environment variable PROJECT_NAME set to MyAwesomeProject

# Now, check if the variable is available in your current shell
echo $PROJECT_NAME
# Output: (nothing, it's empty)

The script ran in a subshell, set the variable, printed the message, and then the subshell closed, taking the variable with it Simple as that..

Scenario 2: Sourcing the Script

# Source the script (no need for +x permission)
source set_env.sh
# Output: Environment variable PROJECT_NAME set to MyAwesomeProject

# Now, check the variable in your current shell
echo $PROJECT_NAME
# Output: MyAwesomeProject

The commands ran directly in your shell. The export command permanently added the variable to your current environment Not complicated — just consistent..

Conclusion

Understanding the fundamental difference between executing a script in a new subshell and sourcing it within your current shell is a cornerstone of effective shell scripting. So Execution (. /script.sh) is for performing self-contained tasks—like running a build, starting a service, or processing data—where changes to the environment are not needed afterward. Consider this: Sourcing (. Consider this: script. Worth adding: sh or source script. Here's the thing — sh) is for integrating scripts into your interactive session, such as loading configurations, setting up development environments, or defining reusable functions and aliases. By mastering this distinction and applying the troubleshooting techniques outlined above, you can confidently write, run, and debug scripts to automate your workflow efficiently Worth keeping that in mind..

This Week's New Stuff

Fresh Reads

You'll Probably Like These

More from This Corner

Thank you for reading about How To Run A Sh File In Terminal. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home