Bash scripting

Bash scripting

How shell scripts in Bash automate repetitive command-line work, such as running a program over many files, moving data and chaining tools, in Linux, macOS and computing clusters.

What it is

Bash (Bourne-Again SHell) is the default command-line interpreter on most Linux systems and was long the default on macOS. A shell reads commands typed by the user, starts programs and passes data between them. A Bash script is a text file of such commands, with variables, loops and conditions, that runs them automatically. Researchers use scripts to process hundreds of data files in one go, to run simulations on computing clusters, to chain tools in bioinformatics and imaging pipelines, to move and back up data, and to record exactly what was done.

It answers questions such as: How do I run the same analysis on 500 files without clicking through each? How do I connect several programs so that the output of one feeds the next? How do I submit many jobs to a supercomputer queue? How do I search and transform large text files quickly? Automation saves time, avoids manual mistakes and makes work reproducible.

Fundamentals

The command line and the file system

Commands have the form command [options] arguments, for example ls -l data/. Essential commands: pwd (current directory), cd (change directory), ls, mkdir, cp, mv, rm (permanent deletion, with no recycle bin), cat, head, tail, less, wc -l (count lines), find, chmod and man command for the manual. Paths are absolute (/home/user/data) or relative (../results), ~ means the home directory, . the current directory and .. the parent. Wildcards (globbing) expand patterns: *.csv matches all CSV files, sample_?.txt matches one character, and {a,b} lists alternatives. Each file has permissions for owner, group and others (read, write, execute), shown by ls -l and changed with chmod +x script.sh.

Pipes, redirection and text tools

Every program has standard input (stdin), standard output (stdout) and standard error (stderr). Redirection sends output to files: > overwrites, >> appends, 2> redirects errors and < reads input from a file. A pipe | connects one command’s output to the next one’s input: cut -f2 data.tsv | sort | uniq -c | sort -nr | head counts the most common values in column 2. The classic text tools are grep (search lines by pattern, with regular expressions; -i ignores case, -v inverts, -r searches directories), sed (stream editing, such as sed 's/old/new/g'), awk (column-based processing, awk -F, '{sum += $3} END {print sum/NR}' file.csv), cut, sort, uniq, tr, paste, join and xargs (turn input lines into arguments, with -P for parallel runs). These tools process large files line by line without loading them into memory.

Script basics: variables, conditions and loops

A script starts with the shebang line #!/usr/bin/env bash, and is run with bash script.sh or ./script.sh after chmod +x. Variables are set without spaces around the equals sign, name="run1", and read with a dollar sign, "$name"; command results are captured with $(date +%F). Arguments are $1, $2, $@ (all) and $# (count). Always quote variables ("$file") so that names with spaces do not break. Conditions use if [[ -f "$file" ]]; then ... elif ...; else ...; fi, with tests such as -f (file exists), -d (directory), -z (empty string), -eq, -lt for numbers and == for strings. Loops: for f in data/*.csv; do python analyze.py "$f"; done, while read -r line; do ...; done < file, and arithmetic $(( i + 1 )). Functions are defined as myfunc() { ...; }, and arrays as files=(a.txt b.txt) with "${files[@]}". Every command returns an exit status (0 means success), available in $?, and && and || chain commands depending on success.

Robust scripting

By default, Bash continues after errors, which can silently produce wrong results. Starting a script with set -euo pipefail makes it stop on errors (-e), on use of unset variables (-u) and on failures inside pipes (pipefail). Other safeguards: check that input files exist, write outputs to new files instead of overwriting, use mktemp for temporary files and trap to clean up, write log messages with timestamps (echo "$(date) start" >> log.txt), use set -x to trace execution, and test on a few files first. Complex logic is better done in Python or R, with Bash used as the “glue” that calls programs.

Scripts in research workflows

Typical patterns: loop over samples to run command-line tools (BLAST, samtools, ImageMagick, ffmpeg); batch-rename files; transfer data with rsync, scp and curl; schedule tasks with cron; connect to servers by ssh; and compress with tar and gzip. On high-performance computing clusters, job scripts for a scheduler such as Slurm contain #SBATCH lines requesting cores, memory and time, followed by commands, and job arrays run the same script for many inputs ($SLURM_ARRAY_TASK_ID selects the file). For bigger pipelines, workflow managers (Make, Snakemake, Nextflow) track dependencies and rerun only what changed. Keep scripts under version control (Git) and record software versions.

Typical applications and limits

Used for data wrangling, pipelines, cluster job submission, system administration and quick tools. Limits include awkward syntax (quoting rules, whitespace sensitivity), no built-in floating-point math or good data structures, slow performance for heavy computation, portability differences (macOS ships an older Bash and BSD versions of tools; Windows needs WSL or Git Bash) and the risk of destructive commands.

Basic operation

  1. Open a terminal. Navigate to the project folder with cd and inspect files with ls and head.
  2. Try commands interactively. Test one command and a pipe on a single file.
  3. Create the script. Save the commands in run.sh with a shebang and set -euo pipefail.
  4. Add variables and a loop. Replace fixed names with "$f" and loop over data/*.csv.
  5. Make it executable. Run chmod +x run.sh.
  6. Test on a small subset. Run with two files and check the outputs and log.
  7. Run the full job. Execute on all files or submit to the cluster queue.
  8. Collect the output. You obtain processed files and a log; pipelines, job arrays and error handling are covered in the video.

Good practice

  • Quote your variables. It avoids bugs with spaces in file names.
  • Use set -euo pipefail. Stop instead of continuing after errors.
  • Test on a small sample. Try new scripts on copies of a few files.
  • Never overwrite raw data. Write results to a separate folder.
  • Comment and log. Record what the script does, the version and the date.
  • Be careful with destructive commands. Double-check rm and mv with echo first, never run scripts from untrusted sources, and avoid putting passwords in scripts.

Key terms

  • Shell — a program that reads commands and runs other programs.
  • Pipe (|) — a connection that sends one command’s output to another command’s input.
  • Redirection — sending input or output to or from files.
  • Globbing — expanding wildcard patterns like *.csv to file names.
  • Exit status — a number returned by a command, with 0 meaning success.
  • Shebang — the first line of a script naming the interpreter to use.
  • Job array — many similar jobs submitted to a cluster scheduler with one script.

Video coming soon

About five minutes on Bash scripting: how it works in detail, how the data is acquired, and how it is analyzed.

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping