Creating Your First Bash Script
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:
- The first line says which program should run the file (the shebang line).
- The file has permission to be executed.
- 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. $1is the first argument given on the command line. When you run./greet.sh Suriya,$1isSuriya.${1:-World}means "use$1, but if it is missing or empty, useWorldinstead". 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 thedatecommand, and%Amakes it print the weekday name. The output replaces the$(...)text, sotodayholds a word such asFriday.- Each
echoprints a line. The double quotes keep the variable's value together and allow$nameand$todayto 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 see | What it means |
|---|---|
Permission denied | The file lacks execute permission. Run chmod +x file. |
command not found | Bash did not find the file. Use ./file, or the full path. |
/usr/bin/env: 'bash\r': No such file or directory | The file uses Windows line endings. |
bash: ./file: cannot execute: required file not found | The shebang line gives a path to a program that does not exist. |
/usr/bin/env: 'name': No such file or directory | The 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.