Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Beginner

Your first script

A shell script is a text file full of terminal commands that run one after another. Anything you'd type by hand (copying files, calling git, restarting a server) can be saved in a script and run again with one word. That's how developers and DevOps engineers automate backups, deployments, reports and server chores.

Bash (the Bourne Again SHell) is the most common shell on Linux servers, in Docker images and in CI pipelines like GitHub Actions. Learn it once and you can automate almost any machine.

💡 About the examples in this track: a web page can't run a real shell, so every example shows its Output underneath. Every script in this track was run with Bash 5.2 on Ubuntu 24.04 to produce that output exactly. Copy them (there's a Copy button) and run them in your own terminal: Linux, macOS, or Windows with WSL. If you're new to the terminal, do the Terminal & Command Line track first.

Hello, script

Create a file called hello.sh with any text editor (nano hello.sh works in every terminal):

hello.sh
#!/usr/bin/env bash
# My first script: prints a greeting and some facts about this machine.

echo "Hello from a script!"
echo "Your home folder is $HOME."
echo "You are logged in as $USER."
echo "Files in this folder: $(ls | wc -l)"

Then make it executable and run it:

bash
chmod +x hello.sh
./hello.sh
Output
Hello from a script!
Your home folder is /home/you.
You are logged in as you.
Files in this folder: 1

Each part has a job:

Part Meaning
#!/usr/bin/env bash The shebang. It must be the very first line: it tells the system which program runs this file. env finds bash wherever it's installed.
# … A comment: Bash ignores everything after # on a line.
echo Prints a line.
$HOME, $USER Variables that hold your home folder and user name.
$(ls | wc -l) Command substitution: runs the commands inside (count the files here) and drops their output into the text.
chmod +x Gives the file permission to be executed as a program. You do it once per script.
./hello.sh Runs the file in the current folder (.).

Why ./?

When you type a command name like ls, the shell only searches the folders listed in your PATH variable (such as /usr/bin). Your current folder isn't one of them, for safety. ./hello.sh gives the exact location instead.

bash
hello.sh
echo "exit code: $?"
Output
bash: hello.sh: command not found
exit code: 127

"Permission denied"

Forget chmod +x and the system refuses to run the file:

bash
chmod -x hello.sh
./hello.sh
echo "exit code: $?"
bash hello.sh          # works: bash reads the file itself
chmod +x hello.sh      # the real fix
./hello.sh
Output
bash: ./hello.sh: Permission denied
exit code: 126
Hello from a script!
Your home folder is /home/you.
You are logged in as you.
Files in this folder: 1
Hello from a script!
Your home folder is /home/you.
You are logged in as you.
Files in this folder: 1

bash hello.sh works without the execute permission because you're running bash and handing it the file to read; the shebang is ignored then. Both ways are fine. chmod +x + ./script is the usual one.

Printing: echo and printf

bash
echo "Plain text"
echo -n "No newline here. "
echo "Same line."
echo -e "Tab:\tafter tab\nSecond line"
printf "%s is %d years old\n" "Asha" 31
printf "%-8s|%6.2f\n" "coffee" 2.5 "tea" 1.75
Output
Plain text
No newline here. Same line.
Tab:	after tab
Second line
Asha is 31 years old
coffee  |  2.50
tea     |  1.75
  • echo is quick for simple lines. -n skips the newline; -e understands \t and \n.
  • printf is like C's printf: %s text, %d whole number, %.2f a decimal with 2 places, %-8s text padded to 8 characters. It needs \n for a newline. When there are more values than placeholders, it repeats the format. That's how the table above got two rows.

💡 Prefer printf in scripts when output matters: echo's options behave differently between shells, but printf is the same everywhere.

Every command has an exit code

When a command finishes it returns an exit code: 0 means success, anything else (1–255) means some kind of failure. $? holds the exit code of the last command. Scripts make decisions with these codes.

bash
ls /etc/hostname
echo "ls worked: $?"
ls /no/such/folder
echo "ls failed: $?"
grep -q root /etc/passwd
echo "grep found it: $?"
Output
/etc/hostname
ls worked: 0
ls: cannot access '/no/such/folder': No such file or directory
ls failed: 2
grep found it: 0

Your script has an exit code too: the one from its last command, or whatever you pass to exit:

check.sh
#!/usr/bin/env bash
if [ -f /etc/os-release ]; then
  echo "This is Linux"
  exit 0
fi
echo "No /etc/os-release here" >&2
exit 1
bash
chmod +x check.sh
./check.sh
echo "check.sh exited with $?"
Output
This is Linux
check.sh exited with 0

(You'll learn if properly in the Conditions lesson. >&2 sends the message to the error stream, covered in Input, output and redirection.)

Chaining commands

Syntax Runs the second command…
a ; b Always, after a finishes
a && b Only if a succeeded (exit code 0)
a || b Only if a failed
bash
mkdir -p demo && cd demo && echo "now in $(pwd)"
cd /nowhere 2>/dev/null || echo "could not cd, carrying on"
true && echo "true succeeds"
false || echo "false fails"
Output
now in /home/you/demo
could not cd, carrying on
true succeeds
false fails

build && deploy is the classic: never deploy a failed build.

Where to keep your scripts

Put personal scripts in ~/bin (or ~/.local/bin) and add that folder to PATH in ~/.bashrc. Then you can run them by name from anywhere:

bash
mkdir -p ~/bin
cp hello.sh ~/bin/hello
export PATH="$HOME/bin:$PATH"   # put this line in ~/.bashrc to make it permanent
hello
Output
Hello from a script!
Your home folder is /home/you.
You are logged in as you.
Files in this folder: 4

The .sh extension is optional: Linux looks at the shebang, not the name. It's a helpful hint for people and editors, so keep it on files inside projects.

Check your scripts with ShellCheck

ShellCheck finds bugs in shell scripts before you run them: missing quotes, typos in variable names, commands that behave differently than you think. Install it (sudo apt install shellcheck, brew install shellcheck) or use the VS Code extension, which underlines problems as you type.

oops.sh
#!/usr/bin/env bash
name=world
echo "Hello $nmae"
bash
shellcheck oops.sh
Output
In oops.sh line 2:
name=world
^--^ SC2034 (warning): name appears unused. Verify use (or export if used externally).


In oops.sh line 3:
echo "Hello $nmae"
            ^---^ SC2154 (warning): nmae is referenced but not assigned.

For more information:
  https://www.shellcheck.net/wiki/SC2034 -- name appears unused. Verify use (...
  https://www.shellcheck.net/wiki/SC2154 -- nmae is referenced but not assign...

Bash itself would happily print Hello and carry on. ShellCheck caught the typo. Every script in this track passes ShellCheck.

Bash, sh, zsh: which shell?

  • Bash is the default on most Linux systems and the one this track teaches (version 4 or newer; Ubuntu ships 5.2).
  • macOS uses zsh for your interactive terminal and ships a very old Bash 3.2. Your scripts still run with Bash because of the shebang. For modern features, brew install bash.
  • sh is the minimal POSIX shell (dash on Ubuntu, ash in Alpine Docker images). Scripts that start with #!/bin/sh must avoid Bash-only features like [[ ]] and arrays. When in doubt, use #!/usr/bin/env bash.

Practice

  1. Write about.sh that prints your user name, the current folder (pwd) and the number of files in it (ls | wc -l).
  2. Use printf to print a three-row price table with names left-aligned in 10 characters and prices with two decimals.
  3. Make the script exit with code 3, then check it with echo $?.
✎ Check your understanding

1.What does the first line #!/usr/bin/env bash do?

2.A command finished with exit code 0. What does that mean?

3.Which line deploys only if the tests pass?