Loops and Variables
45 Minutes
Objectives
- Read and write a
forloop 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
- You can write and submit a batch script. See Submitting Your First Job.
- Following on from Measuring Job Efficiency is useful, but not needed.
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
forloop 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 -eandset -ustop a script at the first error or unset variable.
What next
- Next lesson: Reusable Job Scripts.
- For more shell practice: the Software Carpentry Unix Shell lessons on loops and shell scripts.