Skip to content
Contact Support

Tutorial

Loops and Variables

45 Minutes

Objectives

  • Read and write a for loop that runs a command on each file.
  • Use variables, braces and quotes so values expand the way you expect.
  • Make a script stop on errors and on unset variables.

Prerequisite

Skipped ahead? Set up here

Loops over files

Command substitution

Variables for file paths

Rewrite the loop

Solution

Braces and quotes

#

Braces

What does this print?

number=01
echo $numbersample.txt

Stopping on errors

#

Unset variables

A script starts with set -u and then runs mkdir "${resluts}/vcf", misspelling results. What happens?

Keypoints

  • A for loop runs the same commands on each file.
  • Variables make a script easier to read and to change in one place.
  • Use braces and quotes so variables expand the way you expect.
  • #!/bin/bash -e and set -u stop a script at the first error or unset variable.

What next