Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Your first Bash script: create and run it step by step

By updated

Improve this page

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 if and repeat an action with a loop, for or while
  • 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.

  1. Create a file named hello.sh:

    Terminal window
    nano hello.sh
  2. Write this content:

    #!/bin/bash
    echo "Hello, welcome to $(hostname)!"
  3. Save and exit (Ctrl+O, Enter, Ctrl+X).

  4. Make the file executable:

    Terminal window
    chmod +x hello.sh
  5. Run the script:

    Terminal window
    ./hello.sh
Output
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/bash

It 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:

Terminal window
chmod +x my-script.sh
./my-script.sh

The ./ 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.

Terminal window
bash my-script.sh

The 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/bash
NAME="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.

ConventionExample
Upper case for the script's variablesDIRECTORY, FILE_NAME
Descriptive nameLOG_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/bash
echo "What is your first name?"
read FIRSTNAME
echo "Hello $FIRSTNAME!"

To show the message and the input on the same line, use read -p with the prompt text:

Terminal window
read -p "Your first name: " FIRSTNAME
echo "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:

Terminal window
./greet.sh Alice Bob

These values are available through special variables, numbered in the order of the arguments:

VariableContents
$1First argument (Alice)
$2Second argument (Bob)
$#Number of arguments (2)
$@All the arguments (Alice Bob)
$0Name of the script (./greet.sh)

A complete example, which prints each variable in turn so that you can see what it contains:

#!/bin/bash
echo "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/bash
if [ -z "$1" ]; then
echo "Usage: $0 <name>"
exit 2
fi
echo "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:

CodeMeaning
0Success
1General error
2Misuse (wrong arguments)

To end a script with a given code, use exit followed by the number:

Terminal window
exit 0 # everything went fine
exit 1 # an error occurred

To check the exit code of the last command, print $? right after it:

Terminal window
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 message
NAME="Alice" # Variable holding the first name
echo "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 -h
echo "=== End of report ==="
Terminal window
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:

TestTrue when
-f "$FILE"$FILE exists and is a regular file
-z "$VALUE"$VALUE is empty
"$A" = "$B"the two strings are identical
"$N" -gt 0the 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 missing
for FILE in "$@"; do
if [ -f "$FILE" ]; then
echo "OK: $FILE"
else
echo "MISSING: $FILE"
fi
done
Terminal window
chmod +x check-conf.sh
./check-conf.sh /etc/passwd /etc/missing.conf
Output
OK: /etc/passwd
MISSING: /etc/missing.conf

Look 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:

services.txt
nginx active
cron active
backup inactive
#!/bin/bash
# count-services.sh: counts the active and inactive services of a file
ACTIVE=0
INACTIVE=0
while read -r NAME STATE; do
echo "$NAME is $STATE"
if [ "$STATE" = "active" ]; then
ACTIVE=$((ACTIVE + 1))
else
INACTIVE=$((INACTIVE + 1))
fi
done < "$1"
echo "ACTIVE=$ACTIVE"
echo "INACTIVE=$INACTIVE"
Terminal window
chmod +x count-services.sh
./count-services.sh services.txt
Output
nginx is active
cron is active
backup is inactive
ACTIVE=2
INACTIVE=1

The 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.

SymptomLikely causeFix
Permission deniedScript not executablechmod +x my-script.sh
On WSL, a script in /mnt/c runs without chmod +x, or chmod has no effectLinux permissions are not stored on the Windows driveWork 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 nameRun it with ./script.sh
cannot execute: required file not foundWrong shebang or Windows characters (CRLF)Check #!/bin/bash on the first line, convert with dos2unix
Empty variable in the scriptWrong name or $ forgottenCheck the exact name and the $ in front
[-z: command not foundMissing space after [ in the testWrite [ -z "$1" ] with spaces
Script that prints nothing and does not give the prompt backA read is waiting for your input, or an endless loopType 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 found

The 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 denied

The exit code is then 126, the one for a command that was found but cannot be executed.

Terminal window
file my-script.sh # "with CRLF line terminators" gives the culprit away
dos2unix my-script.sh

Put 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 +x makes the file executable, ./script.sh runs it.
  • Variables (NAME="value") and arguments ($1, $2) make a script flexible.
  • read asks for input, echo prints a result.
  • if [ ... ]; then ... fi tests a condition (-f, -z, =, -gt), for repeats an action over a list, while read reads a file line by line.
  • exit 0 signals a success, any non-zero value an error (1 general error, 2 misuse), which you can test with echo $?.
  • 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

6 questions
6 min
70% to pass

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