Skip to content
shellhacks.dev
Bash

How to Write and Run Your First Bash Script on Linux

Write a Bash script in a text editor, save it with the right first line, and run it three different ways, with the permission error explained.

6 min read
Summarize in AI
Illustration for "How to Write and Run Your First Bash Script on Linux": a shell script in an editor, file permission bits, an exit status badge.

A Bash script is a plain text file, and the only things that separate it from any other text file are a first line and a permission bit. People lose an hour to the two errors that come from getting either wrong, so here is the short version first, and the reasoning after it. The broader path is in Bash scripting from zero to a script you trust.

These steps assume Bash 5.2 on Debian 13, and they behave the same on any current Linux distribution and on macOS with its older Bash 3.2.

Create the file

Open any editor. nano is installed nearly everywhere.

Shell
nano disk-report.sh

Type the script, then save and exit.

disk-report.shShell
#!/usr/bin/env bash
echo "Disk usage for $HOME:"
du -sh "$HOME" 2>/dev/null

The 2>/dev/null hides permission warnings for folders you cannot read. Remove it if you want to see them.

Three ways to run it

CommandNeeds execute bitUses the shebang
bash disk-report.shNoNo
./disk-report.shYesYes
source disk-report.shNoNo, and it runs in your current shell

The first is the safest way to try a script you just wrote. The second is how scripts are installed for daily use. The third is for scripts that must change your current shell, such as one that sets environment variables, and it is the wrong choice for everything else because variables and cd calls leak into your session.

Shell
chmod +x disk-report.sh
./disk-report.sh

Why ./ is required

Typing disk-report.sh alone fails with command not found, because the shell looks for commands only in the directories listed in PATH, and the current directory is not one of them. That is deliberate: if it were, a malicious file named ls in a shared folder would run in place of the real one. The ./ prefix gives an explicit path, which skips the search.

Install it where you can call it by name

Shell
mkdir -p ~/.local/bin
mv disk-report.sh ~/.local/bin/disk-report
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

Open a new terminal, or run source ~/.bashrc, and disk-report now works from any folder. Dropping the extension is a convention, not a rule; a command named disk-report reads better than disk-report.sh, and you can rewrite it in another language later without changing the name. Which file Bash reads at startup depends on the kind of shell, which how Bash reads startup files explains.

When it does not run

MessageCauseFix
Permission deniedExecute bit missingchmod +x
command not foundNot in PATHUse ./name or install into a PATH folder
bad interpreter: No such file or directoryWindows line endings after the shebangsed -i 's/\r$//' file

The line-ending case is common when a file was saved on Windows. The kernel reads the interpreter as bash followed by a carriage return, which is not a real program. The sed -i form above is GNU sed; on macOS, BSD sed needs -i ''.

What the kernel and the shell each do

Running a script involves two programs, and mixing them up is behind most of the confusing errors. When you type ./disk-report.sh, your interactive shell asks the kernel to execute the file. The kernel checks the execute permission, reads the first line, finds the interpreter named after #! and starts it with the script path as its argument. That interpreter, here Bash, then reads the rest of the file. The shell you typed in is only the messenger. It waits for the child to finish and picks up its exit status.

The same lookup explains why a script with no shebang still often works when you run it from a terminal. If the kernel refuses the file with an exec format error, many shells fall back to running it themselves, and the result depends on which shell that is. A script that behaves differently when launched by cron, which uses /bin/sh, than from your prompt almost always lacks a shebang.

Prove which interpreter is running

Do not assume. Add one line that asks Bash for its version, and run the script both ways.

who-runs-me.shShell
#!/usr/bin/env bash
echo "interpreter: $BASH"
echo "version: $BASH_VERSION"
echo "script name: $0"
echo "argument count: $#"
Shell
chmod +x who-runs-me.sh
./who-runs-me.sh one two
bash who-runs-me.sh one two
Text
interpreter: /usr/bin/bash
version: 5.2.37(1)-release
script name: ./who-runs-me.sh
argument count: 2
interpreter: /usr/bin/bash
version: 5.2.37(1)-release
script name: who-runs-me.sh
argument count: 2

Both runs report the same Bash, and only $0 differs, because it holds the path exactly as it was typed. Now change line one to #!/bin/sh and run ./who-runs-me.sh again on Debian. The script fails, since BASH and BASH_VERSION are empty under dash, and $BASH expands to nothing. That is the quickest way to see that the shebang, not the file extension, picks the language.

Passing arguments and reading input

A script that does one fixed thing is a macro. It becomes a tool when it accepts arguments. Positional parameters $1 to $9 hold what followed the script name, "$@" expands to all of them with their spaces preserved, and $# counts them. Keep the quotes around "$@", because the unquoted form splits an argument like "my report.txt" into two.

size-of.shShell
#!/usr/bin/env bash
if [[ $# -eq 0 ]]; then
  echo "usage: size-of.sh FILE..." >&2
  exit 2
fi
du -sh "$@"
Shell
./size-of.sh
echo "exit status: $?"
Text
usage: size-of.sh FILE...
exit status: 2

Exit status 2 for a usage mistake follows the convention most Unix tools use, and it lets a caller tell a bad invocation from a runtime failure, which usually exits with 1. The usage line goes to standard error so that it never lands in a file when the user redirects output.

Where scripts live as they multiply

Once there are five scripts, the folder they sit in matters. A common layout is ~/.local/bin for scripts you run by name, with the source tracked in a Git repository elsewhere and linked in with ln -s. Linking keeps one copy to edit, and the PATH entry stays stable. Whatever the layout, avoid names that shadow real commands. A script called test or backup in a PATH folder that comes first can replace the system command in every other script you run. Check a name before using it with type -a name, which lists every match in order.

One more check before you share it

Run the script once with bash -n to catch syntax errors and once under shellcheck if you have it. Then run it from a different directory than the one you wrote it in, because a script that only works from its own folder has a relative path in it somewhere.

When a script is the wrong tool

A script that grows past a few hundred lines, parses JSON by hand or needs real data structures is better in Python or Go. The decision is laid out in when a Bash script should become Python. For everything shorter, the script file, the shebang and the execute bit are the whole mechanism. The Bash manual section on executing commands describes the lookup in full, and the POSIX shell command language defines the rules a portable script can rely on.

Share

Keep reading

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.