Please enable JavaScript to use CodeHS

Terminal & Bash — Tutorial 4

Bash Scripts

A script is a text file containing many terminal commands that can be run together. Instead of typing the same five commands every morning, you save them in a file and run the file. Scripts turn your terminal from a control panel into a toolkit you can reuse and share.

Why write scripts?

Programs you write in Python or JavaScript are great, but many real-world tasks are easier to express as a sequence of shell commands. For example:

  • backing up a folder before you edit it,
  • renaming a batch of files,
  • running tests, building, and deploying with one command,
  • setting up a new computer the same way every time.

Scripts are also the glue that connects other programs. A short script can call Python, Node, Git, and Docker in the right order.

Your first script

A Bash script usually starts with a line called a shebang that tells the computer which interpreter to use. The rest of the file is ordinary Bash.

hello.sh
#!/bin/bash
echo "Hello, terminal!"

Save it as hello.sh, then make it executable with chmod +x hello.sh and run it with ./hello.sh. The ./ tells the shell to look for the program in the current directory.

Variables and arguments

Variables store values. In Bash, you write them without spaces around the equals sign, and you read them with a dollar sign.

Variables
NAME="CodeHS"
echo "Hello, $NAME!"

When you run ./greet.sh Ada, the first argument is available as $1. The second is $2, and so on. The special variable $@ means "all the arguments."

Loops and conditionals

A loop repeats a command for each item in a list. A conditional runs a command only when a test is true.

backup.sh
#!/bin/bash
SOURCE="data"
BACKUP="backups/$SOURCE-$(date +%Y%m%d)"

if [ ! -d "backups" ]; then
  mkdir backups
fi

cp -r "$SOURCE" "$BACKUP"
echo "Backed up to $BACKUP"

This script creates a backup folder if it does not exist, then copies data into a folder whose name includes today's date.

Running a script

There are two common ways to run a script:

  • bash script.sh — run it with Bash, even if the file is not executable.
  • ./script.sh — run it directly, but the file needs execute permission from chmod +x script.sh.

The dot-slash is a safety feature. It prevents the shell from accidentally running a program in your current folder when it has the same name as a common command.

Try the script lab

The simulator below has two scripts ready to run: hello.sh and backup.sh. Try running them. You can also create your own script with touch myscript.sh if you want, although the simulator will not execute custom scripts.

bash — ~/home

Quick quiz

1. What is the first line of a Bash script called?

2. How do you read a variable in Bash?

3. Which command makes a script executable?

Keep learning

You can write, save, and run Bash scripts that automate real tasks. You are ready to use the terminal as a daily tool.

Final tutorial in the “Terminal & Bash” series.