Never written a script? This page takes you to a first Bash script that works: a file, a shebang line, the execute permission, and it runs. In a few minutes, you will know how to create, make executable and run a script, with variables, arguments, conditions and loops, with no programming background at all. The lesson shows the basics: the complete Bash shell scripting guide, at level 2, goes further (more tests, functions).
What you will learn
- Create a script with the shebang
#!/bin/bash - Make it executable with
chmod +x - Use variables to store values
- Read user input with
read - Get the arguments passed to the script
- Test a condition with
ifand repeat an action with a loop,fororwhile - Exit cleanly with an exit code
How do you create a minimal script?
A script is nothing more than a text file holding the commands you would
have typed by hand. The 5 steps below produce a complete one, and two of
them often surprise people: the file must receive the execute permission,
and running it takes a ./ in front of its name.
-
Create a file named
hello.sh:Terminal window nano hello.sh -
Write this content:
#!/bin/bashecho "Hello, welcome to $(hostname)!" -
Save and exit (Ctrl+O, Enter, Ctrl+X).
-
Make the file executable:
Terminal window chmod +x hello.sh -
Run the script:
Terminal window ./hello.sh
Hello, welcome to server01!What is the shebang?
The first line of a script must be the shebang, which names the interpreter that will read the rest of the file:
#!/bin/bashIt tells the system which interpreter to use to run the file. Without this line, the kernel does not know which interpreter to choose: run from Bash, the script often executes anyway, but the result depends on the shell that launches it. The shebang makes the choice explicit.
How do you make a script executable and run it?
By default, a new file is not executable. Two steps are needed:
chmod +x my-script.sh./my-script.shThe ./ tells the shell to look for the file in the current directory.
Without it, the shell only looks in the directories listed in the PATH
variable (the list of places where it looks for commands), and the current
directory is generally not one of them: it answers command not found.
There is an alternative, useful when you are not allowed to change the file's permissions: call Bash directly on the script.
bash my-script.shThe interpreter is then chosen by the command, not by the shebang,
which is simply ignored. It is handy for a quick test, but the standard
method remains chmod +x followed by ./my-script.sh: it makes the script
usable like any other command.
How do you use variables?
A variable stores a value so you can reuse it, and $(...) fills one with the output of a command:
#!/bin/bashNAME="Alice"MACHINE=$(hostname)echo "Hello $NAME, you are on $MACHINE"Rules:
- No spaces around the
= - To read the value:
$NAME $(command)captures the result of a command
Naming good practices
Bash imposes only one rule on the name: it contains only letters, digits and
_, and does not start with a digit. MY-VAR=1 is therefore not an
assignment: Bash reads it as a command and answers MY-VAR=1: command not found. The other conventions are not enforced: they exist so that the script
stays readable months later, by you or by someone else. Remember above all
the second one in the table, a descriptive name, because it removes the need to go back
up the code to find out what a variable holds.
| Convention | Example |
|---|---|
| Upper case for the script's variables | DIRECTORY, FILE_NAME |
| Descriptive name | LOG_FILE rather than F |
Words separated by _ | FILE_NAME rather than FILE-NAME (the dash is forbidden) |
How do you read user input?
The read command pauses the script and waits for the user to type
something:
#!/bin/bashecho "What is your first name?"read FIRSTNAMEecho "Hello $FIRSTNAME!"To show the message and the input on the same line, use read -p with the prompt text:
read -p "Your first name: " FIRSTNAMEecho "Hello $FIRSTNAME!"If no message comes before the read, the script prints nothing: it seems
frozen while it is waiting for your input. Type a value then Enter, or
Ctrl+C to interrupt it.
How do you pass arguments to a script?
A script can receive values when it is launched, written after its name:
./greet.sh Alice BobThese values are available through special variables, numbered in the order of the arguments:
| Variable | Contents |
|---|---|
$1 | First argument (Alice) |
$2 | Second argument (Bob) |
$# | Number of arguments (2) |
$@ | All the arguments (Alice Bob) |
$0 | Name of the script (./greet.sh) |
A complete example, which prints each variable in turn so that you can see what it contains:
#!/bin/bashecho "Script: $0"echo "Argument 1: $1"echo "Argument 2: $2"echo "Number of arguments: $#"Check that an argument is given
A script that needs arguments checks that they are present, and stops with a usage message otherwise:
#!/bin/bashif [ -z "$1" ]; then echo "Usage: $0 <name>" exit 2fiecho "Hello $1!"-z "$1" tests whether the first argument is empty. If so, the script
prints a help message and stops with code 2, the one for misuse (see the
table of exit codes below). Run without an argument, the script therefore
returns 2: echo $? shows it right afterwards. The quotes around $1
matter: an argument that contains a space, without quotes, would cause the
error too many arguments.
How do exit codes work?
Every command (and every script) returns an exit code. Three values cover the needs of a first script:
| Code | Meaning |
|---|---|
0 | Success |
1 | General error |
2 | Misuse (wrong arguments) |
To end a script with a given code, use exit followed by the number:
exit 0 # everything went fineexit 1 # an error occurredTo check the exit code of the last command, print $? right after it:
echo $?How do you write comments?
A comment starts with #. The shell ignores everything that follows on the
line:
#!/bin/bash# This script prints a welcome messageNAME="Alice" # Variable holding the first nameecho "Hello $NAME"Comment your code to explain why you do something, not what (the code already shows that).
Complete example: system report
Here is a concrete script that gathers information about the system, then the two commands that run it:
#!/bin/bash# system-report.sh: shows a summary of the system state
echo "=== System report ==="echo "Date : $(date)"echo "Machine : $(hostname)"echo "User : $USER"echo "Directory: $PWD"echo ""echo "Disk space:"df -h /echo ""echo "Memory:"free -hecho "=== End of report ==="chmod +x system-report.sh./system-report.sh$USER and $PWD are variables that the shell fills in itself: the name of
the logged-in account and the current directory. The rest of the script only
chains commands you can also type by hand. That is the principle of a script:
automate a sequence of repetitive tasks.
How do you repeat an action and test a condition?
A condition (if) makes the script choose between two paths, and a
loop (for or while) makes it repeat commands. Both are needed as soon
as you have to process several files or several lines, without rewriting the
same command each time.
The form of a condition is if [ test ]; then, followed by the commands to
run, then fi to close the block. The spaces after [ and before ] are
mandatory: the troubleshooting table below shows the error that forgetting
them causes. Four tests are enough to get started:
| Test | True when |
|---|---|
-f "$FILE" | $FILE exists and is a regular file |
-z "$VALUE" | $VALUE is empty |
"$A" = "$B" | the two strings are identical |
"$N" -gt 0 | the number $N is strictly greater than 0 |
The for loop takes the items of a list one by one. With "$@", the list is
the script's arguments. This script checks that configuration files exist:
#!/bin/bash# check-conf.sh: reports the configuration files that are missingfor FILE in "$@"; do if [ -f "$FILE" ]; then echo "OK: $FILE" else echo "MISSING: $FILE" fidonechmod +x check-conf.sh./check-conf.sh /etc/passwd /etc/missing.confOK: /etc/passwdMISSING: /etc/missing.confLook at the order of the lines: the loop processes the arguments in the order
you wrote them, and the -f test gives a different result for each one. If
MISSING shows for a file that exists, check the quotes around "$FILE" and
the spelling of the path.
To read a file line by line, use while read instead. On each turn,
read splits the line into words and stores them in variables, until the end
of the file. The file is given to the loop with < "$1" after done. To
count, a variable starts at 0 and grows by 1 with $(( ... )), the shell's
integer arithmetic. The following example reads a file that lists services and
their state. First create this file with nano services.txt, type the three
lines below (a name, a space, then the state), and save as you did for
hello.sh:
nginx activecron activebackup inactive#!/bin/bash# count-services.sh: counts the active and inactive services of a fileACTIVE=0INACTIVE=0while read -r NAME STATE; do echo "$NAME is $STATE" if [ "$STATE" = "active" ]; then ACTIVE=$((ACTIVE + 1)) else INACTIVE=$((INACTIVE + 1)) fidone < "$1"echo "ACTIVE=$ACTIVE"echo "INACTIVE=$INACTIVE"chmod +x count-services.sh./count-services.sh services.txtnginx is activecron is activebackup is inactiveACTIVE=2INACTIVE=1The script counts, but it always ends with code 0, even when a service is
inactive. For an automation tool to know that something is wrong, you would
combine this counter with a -gt test and an exit followed by a code, as in
the argument check above: that is what the lab asks you to put together. The -r option of read stops the shell from
interpreting backslashes: make a habit of using it. If the condition never
triggers although the file does contain active, look for a typo or a capital
letter in the file (Active): the = test compares the exact word,
capitals included.
Troubleshooting
The failures of a first script all look alike: the file is there, its
contents seem correct, and nothing runs. Three rows of the table give the
causes: a missing execute permission, a forgotten ./ in front of the
name, or a file saved with Windows line endings. None of them comes from
the code itself.
| Symptom | Likely cause | Fix |
|---|---|---|
Permission denied | Script not executable | chmod +x my-script.sh |
On WSL, a script in /mnt/c runs without chmod +x, or chmod has no effect | Linux permissions are not stored on the Windows drive | Work in ~, or enable the metadata option in /etc/wsl.conf (see the note above) |
command not found when running script.sh | ./ missing in front of the name | Run it with ./script.sh |
cannot execute: required file not found | Wrong shebang or Windows characters (CRLF) | Check #!/bin/bash on the first line, convert with dos2unix |
| Empty variable in the script | Wrong name or $ forgotten | Check the exact name and the $ in front |
[-z: command not found | Missing space after [ in the test | Write [ -z "$1" ] with spaces |
| Script that prints nothing and does not give the prompt back | A read is waiting for your input, or an endless loop | Type a value then Enter, or Ctrl+C to interrupt |
Messages for a missing or non-executable interpreter
Older tutorials quote bad interpreter: No such file or directory. With
Bash 5.2.37 on Debian 13, that text no longer appears when the shebang
interpreter is missing. Bash shows the same message for a wrong shebang
and for a file saved with Windows line endings:
bash: ./my-script.sh: cannot execute: required file not foundThe exit code is 127. In a non-interactive shell (a command run through
ssh, for example), the message also carries a line 1: prefix. The cause
stays the same: the kernel cannot find the interpreter given after the #!.
In the CRLF case, the interpreter looked for is literally /bin/bash\r, with
an invisible carriage return at the end, hence a file "not found" although
/bin/bash does exist.
The bad interpreter message still exists in another case: the interpreter is
present but lacks the x permission. With a #!/bin/nonexec shebang
pointing to a file in 644, Bash 5.2.37 answers:
bash: ./my-script.sh: /bin/nonexec: bad interpreter: Permission deniedThe exit code is then 126, the one for a command that was found but cannot be executed.
file my-script.sh # "with CRLF line terminators" gives the culprit awaydos2unix my-script.shPut it into practice
You only understand a script by writing it yourself, then running it on real data. This lab has you produce a report.sh that reads a status file passed as an argument, counts the UP/DOWN hosts with a loop and a condition, then returns a non-zero exit code as soon as a host is down. Your script is compared with the expected behaviour. The section "How do you repeat an action and test a condition?" gives the ingredients (if, a while read loop, a counter), and the section on arguments shows how to exit with a code: it is up to you to put them together.
Key points
- A script starts with
#!/bin/bash(the shebang), which identifies the interpreter. chmod +xmakes the file executable,./script.shruns it.- Variables (
NAME="value") and arguments ($1,$2) make a script flexible. readasks for input,echoprints a result.if [ ... ]; then ... fitests a condition (-f,-z,=,-gt),forrepeats an action over a list,while readreads a file line by line.exit 0signals a success, any non-zero value an error (1general error,2misuse), which you can test withecho $?.- Comment your scripts to make them understandable.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Linux users, permissions and processes
A new full quiz with random questions
Work again only on the questions you missed