Level 2 · Code & compute · Topic 1 of 6

The Linux command line for biologists

Files, paths, permissions and the core commands for inspecting large biological files.

  • About 90 minutes
  • 7 practice terminals · 31 checked tasks
  • 1 terminal recording
  • 10-question check
  • Runs in your browser

What you will learn

  • Explain what a shell, a terminal and a command are, and read any command as a program, its options and its arguments.
  • Move around the filesystem with pwd, ls and cd, using absolute and relative paths, ~, . and ..
  • Create, copy, move and remove files and directories safely, and lay out a project so the raw data stay untouched.
  • Look inside large biological files without opening them whole, with head, tail, less, wc and zcat.
  • Select many files at once with wildcards, and search a directory tree with find.
  • Read and change file permissions, and make raw data read-only.

Before you start: None beyond Level 1. You do not need to have used a terminal before, and you do not need to install anything: the practice terminals on this page run in your browser.

Why the command line?

Most bioinformatics happens at a command line. Sequencing runs produce files far too large for a spreadsheet or a text editor: a single human genome sequenced to 30× coverage is about 100 gigabytes of compressed reads. The programs that align, assemble and call variants (BWA, SAMtools, GATK, BLAST and hundreds more) are command-line programs, and the servers and computing clusters they run on usually have no graphical desktop at all.

The command line also makes your work reproducible. A command is a precise, written record of what you did: you can save it, rerun it next year, share it with a colleague or put it in a script that processes a thousand samples overnight. Clicking through menus leaves no such record.

This topic teaches the commands you will use every day, on the same kinds of files you will meet in real projects. On this page they run on real data: the SARS-CoV-2 reference genome, Illumina reads from the E. coli long-term evolution experiment, fruit-fly RNA-seq counts and more.

Watch first: a tour of the practice files. A one-minute recording of a terminal session. Every command was run by GNU Bash 5.3 and GNU coreutils 9.12 on the same files you will use below; pause it at any point, or read the transcript. Download the recording
Read the transcript
learner@quanexas:~$ # Where am I? pwd prints the working directory
learner@quanexas:~$ pwd
/home/learner
learner@quanexas:~$ ls
README.txt  data
learner@quanexas:~$ ls data
beta-globin-locus  ecoli-k12  hbb  hbb-variants  lenski  pasilla  sars-cov-2  structures
learner@quanexas:~$ # Move into a dataset and list it in long form, with readable sizes
learner@quanexas:~$ cd data/sars-cov-2
learner@quanexas:~/data/sars-cov-2$ ls -lh
-rw-r--r-- 1 learner learner 30K Oct 28 09:00 NC_045512.2.fasta
-rw-r--r-- 1 learner learner 77K Oct 28 09:00 NC_045512.2.gb
-rw-r--r-- 1 learner learner 15K Oct 28 09:00 NC_045512.2.gff3
learner@quanexas:~/data/sars-cov-2$ # A FASTA file: a header line starting with >, then the sequence
learner@quanexas:~/data/sars-cov-2$ head -n 3 NC_045512.2.fasta
>NC_045512.2 Severe acute respiratory syndrome coronavirus 2 isolate Wuhan-Hu-1, complete genome
ATTAAAGGTTTATACCTTCCCAGGTAACAAACCAACCAACTTTCGATCTCTTGTAGATCTGTTCTCTAAA
CGAACTTTAAAATCTGTGTGGCTGTCACTCGGCTGCATGCTTAGTGCACTCACGCAGTATAATTAATAAC
learner@quanexas:~/data/sars-cov-2$ wc -l NC_045512.2.fasta
430 NC_045512.2.fasta
learner@quanexas:~/data/sars-cov-2$ # Gzip-compressed reads: look inside without unpacking them
learner@quanexas:~/data/sars-cov-2$ cd ~/data/lenski
learner@quanexas:~/data/lenski$ zcat SRR2584863_1.first10k.fastq.gz | head -n 4
@SRR2584863.1 HWI-ST957:244:H73TDADXX:1:1101:4712:2181/1
TTCACATCCTGACCATTCAGTTGAGCAAAATAGTTCTTCAGTGCCTGTTTAACCGAGTCACGCAGGGGTTTTTGGGTTACCTGATCCTGAGAGTTAACGGTAGAAACGGTCAGTACGTCAGAATTTACGCGTTGTTCGAACATAGTTCTG
+
CCCFFFFFGHHHHJIJJJJIJJJIIJJJJIIIJJGFIIIJEDDFEGGJIFHHJIJJDECCGGEGIIJFHFFFACD:BBBDDACCCCAA@@CA@C>C3>@5(8&>C:9?8+89<4(:83825C(:A#########################
learner@quanexas:~/data/lenski$ zcat SRR2584863_1.first10k.fastq.gz | wc -l
40000
learner@quanexas:~/data/lenski$ # Four lines per read, so 40000 lines is 10000 reads
learner@quanexas:~/data/lenski$ cd
learner@quanexas:~$ pwd
/home/learner
learner@quanexas:~$

The shell, the terminal and commands

A terminal is the window you type into. The shell is the program inside it that reads what you type, runs it and shows you the result. The shell on almost every Linux system, and the one used here, is Bash (the Bourne-Again SHell). When it is ready for a command it shows a prompt:

learner@quanexas:~$

That is the user name, the computer's name, the directory you are in (~ is short for your home directory) and $, which means "type here". A command is a line of words separated by spaces. The first word names the program; the rest are its options, which change how it behaves and usually start with -, and its arguments, which are usually the files or directories it should work on.

Short options can be combined, so ls -l -h and ls -lh are the same command. Many options also have a long form that is easier to read in scripts: ls --human-readable is ls -h. Spaces matter, and so does case: LS is not ls, and Data is not data.

You never need to remember every option. Every command explains itself: ls --help prints a summary, man ls opens its manual (press q to leave), and in the practice terminal help lists every command you can use.

Practice terminal

Your first commands

Click the terminal and type each command, then press Enter. Tasks tick themselves off when your command produces the right result; you can type your own variations too.

learner@quanexas: ~
  1. Print the directory you are in with pwd (print working directory).

    Hint

    Type pwd and press Enter.

    Show the answer
    pwd
  2. List what is in your home directory with ls.

    Show the answer
    ls
  3. List the contents of the data directory.

    Hint

    Give ls the directory as an argument.

    Show the answer
    ls data
  4. Show the files in data/lenski in long format with human-readable sizes, using two options.

    Hint

    -l gives the long format and -h readable sizes. You can write them as -lh.

    Show the answer
    ls -lh data/lenski

    Each line shows the permissions, the number of links, the owner and group, the size, the date it was last changed and the name. You will read the permissions in the last section.

Moving around: the filesystem and paths

Linux keeps every file in one tree of directories (folders). The top of the tree is the root, written /. Your own files live in your home directory, here /home/learner, which the shell lets you write as ~. At any moment the shell has a working directory, the one pwd prints, and every command runs there.

A path says where a file is. An absolute path starts at the root with / and means the same thing wherever you are: /home/learner/data/hbb/P68871.fasta. A relative path starts from the working directory: from /home/learner, the same file is data/hbb/P68871.fasta. Two special names help: . is the current directory and .. is the one above it.

CommandWhat it does
cd data/hbbGo into data/hbb, below the working directory
cd ..Go up one level; cd ../.. goes up two
cd /home/learner/dataGo to an absolute path, from anywhere
cd ~/data/lenskiA path from your home directory, from anywhere
cdGo home (the same as cd ~)
cd -Go back to the directory you were in before

Interactive

Path explorer

Pick a working directory and type a path, or choose one of the examples. The explorer works out where the path leads, one step at a time, using the same files as the practice terminal.

Practice terminal

Moving around

Watch the prompt: it always shows where you are.

learner@quanexas: ~
  1. Move into the SARS-CoV-2 dataset, data/sars-cov-2.

    Hint

    cd followed by the path. Press Tab to complete the names.

    Show the answer
    cd data/sars-cov-2
  2. From there, go back up to your home directory with a relative path that uses ..

    Hint

    Each .. is one level up, and you are two levels below home.

    Show the answer
    cd ../..
  3. Without moving, list data/hbb using its absolute path, which starts with /.

    Hint

    Your home directory is /home/learner.

    Show the answer
    ls /home/learner/data/hbb
  4. Jump straight to the lenski dataset with a path that starts with ~.

    Show the answer
    cd ~/data/lenski
  5. Go back to the directory you were in before with cd -.

    Show the answer
    cd -

Organising a project: creating, copying, moving and removing

A tidy project makes analyses easier to follow and safer to repeat. A common layout keeps the original data apart from everything you make from it, so the raw files are never edited by mistake:

project/
├── data/       original files, never changed
├── results/    output of your analyses, which can always be remade
├── scripts/    the commands that make the results
└── README.md   what the project is and how to run it

These commands build and rearrange such a tree:

CommandWhat it does
mkdir resultsMake a directory. mkdir -p a/b/c makes the parents too, and does not complain if they exist
touch notes.txtMake an empty file (or update the date of an existing one)
cp source targetCopy a file; cp -r copies a directory and everything in it
mv old newMove a file or directory, or rename it: there is no separate rename command
rm fileRemove a file; rm -r dir removes a directory and everything in it; rmdir removes an empty directory

The shell can also write several similar names for you with brace expansion: mkdir -p project/{data,results,scripts} is the same as typing mkdir -p project/data project/results project/scripts.

Practice terminal

Lay out a project

learner@quanexas: ~
  1. Make project/data, project/results and project/scripts with one mkdir command.

    Hint

    -p creates project as well, and braces write the three names for you.

    Show the answer
    mkdir -p project/{data,results,scripts}
  2. Copy the SARS-CoV-2 genome, data/sars-cov-2/NC_045512.2.fasta, into project/data.

    Hint

    cp takes the file to copy, then where to put it.

    Show the answer
    cp data/sars-cov-2/NC_045512.2.fasta project/data/
  3. Rename the copy to project/data/sars-cov-2.fasta.

    Hint

    Renaming is moving to a new name: mv old new.

    Show the answer
    mv project/data/NC_045512.2.fasta project/data/sars-cov-2.fasta
  4. Show the whole project as a tree with tree project.

    Show the answer
    tree project

Looking inside big files

Biological files are mostly plain text, but they are big: opening a 4 GB FASTQ file in an editor can freeze your computer. The command line lets you look at just the part you need. The commands below read a file from start to end without loading it all, so they work on files of any size.

CommandShows
head -n 5 fileThe first 5 lines (10 if you leave out -n)
tail -n 5 fileThe last 5 lines; tail -n +2 starts at line 2, which skips a header
less fileThe file a screen at a time: Space for the next page, / to search, q to quit
wc -l fileHow many lines it has (wc alone also counts words and bytes)
cat fileThe whole file: only sensible for small files
zcat file.gzThe contents of a gzip-compressed file, without unpacking it on disk

The formats you met in Level 1 look like this from the command line. A FASTA file has a header line starting with >, then the sequence on as many lines as it takes: the SARS-CoV-2 genome file has 430 lines: the header, 428 lines of sequence (70 bases each, except the last, which holds the final 13) and a blank line at the end. A FASTQ file has exactly four lines per read: a header starting with @, the bases, a + line and one quality character per base. That makes counting reads easy: lines divided by four.

Sequencing data are almost always stored compressed with gzip, which is why their names end in .gz. The reads in data/lenski take 1.2 MB compressed and 3.65 MB unpacked; gzip -l shows both sizes. Never decompress large files just to look at them: zcat streams the contents, and the pipe, |, sends them straight into another command, as in zcat reads.fastq.gz | head -n 4. The next topic is all about pipes.

Practice terminal

Look before you analyse

This terminal starts in ~/data.

learner@quanexas: ~/data
  1. Show the first 2 lines of sars-cov-2/NC_045512.2.fasta: the header and the first line of sequence.

    Show the answer
    head -n 2 sars-cov-2/NC_045512.2.fasta
  2. Count the lines in the annotation file sars-cov-2/NC_045512.2.gff3.

    Hint

    wc -l counts lines.

    Show the answer
    wc -l sars-cov-2/NC_045512.2.gff3
  3. Show the first read (4 lines) of lenski/SRR2584863_1.first10k.fastq.gz without decompressing the file, by piping zcat into head.

    Hint

    zcat file | head -n 4

    Show the answer
    zcat lenski/SRR2584863_1.first10k.fastq.gz | head -n 4
  4. Count the lines in the same compressed file. How many reads does it hold?

    Hint

    Pipe zcat into wc -l, then divide by four.

    Show the answer
    zcat lenski/SRR2584863_1.first10k.fastq.gz | wc -l
  5. Show the last 3 lines of the sample sheet pasilla/pasilla_sample_annotation.csv.

    Show the answer
    tail -n 3 pasilla/pasilla_sample_annotation.csv
  6. Open sars-cov-2/NC_045512.2.gff3 in less, search for Name=S; (the spike gene) by typing /Name=S;, then press q to come back.

    Show the answer
    less sars-cov-2/NC_045512.2.gff3

Many files at once: wildcards and find

Projects have dozens or thousands of files with similar names. Wildcards (also called globs) describe a set of names: * matches any characters, ? exactly one, and [12] one of the characters in the brackets. So *.fastq.gz means "every name ending in .fastq.gz", and sample_?.txt matches sample_1.txt but not sample_10.txt.

It is the shell that expands a wildcard, before the command runs: ls data/*/*.fasta becomes ls followed by six file names. echo shows you what a pattern expands to without doing anything to the files, which makes it a good safety check before rm. If nothing matches, Bash leaves the pattern as it is.

When files are spread through many directories, find searches the whole tree: find data -name '*.gz' lists every gzip file below data, and you can add conditions such as -type d (directories only) or -size +1M (larger than 1 MiB). Quote the pattern so that the shell passes it to find instead of expanding it. du -sh shows how much space files and directories use.

Practice terminal

Find the files

learner@quanexas: ~
  1. List every FASTA file in all the dataset directories with one wildcard pattern: ls data/*/*.fasta.

    Show the answer
    ls data/*/*.fasta
  2. Count them by piping the list into wc -l.

    Show the answer
    ls data/*/*.fasta | wc -l
  3. Use find to list every file below data whose name ends in .gz.

    Hint

    find data -name '*.gz'. The quotes keep the shell from expanding the pattern itself.

    Show the answer
    find data -name '*.gz'
  4. Show how much space each dataset takes with du -sh data/*.

    Show the answer
    du -sh data/*

Permissions: protecting your raw data

Every file and directory belongs to a user and a group, and has three sets of permissions: for its owner (user), for members of its group, and for everyone else (others). Each set says whether they may read, write or execute it. ls -l shows them as the first column:

-rw-r--r-- 1 learner learner 236 Oct 28 09:00 P68871.fasta
│└┬┘└┬┘└┬┘
│ │  │  └ others: read only
│ │  └ group: read only
│ └ owner (learner): read and write
└ - for a file, d for a directory

For a directory the letters mean something slightly different: r lets you list the names in it, w lets you create, rename and delete entries in it, and x lets you enter it with cd and reach the files inside.

chmod changes permissions, either with letters, as in chmod u+x script.sh (let the owner execute it) and chmod a-w data.fastq.gz (take write permission away from all), or with three octal digits, one per set, where read is 4, write 2 and execute 1: chmod 644 means rw-r--r-- and chmod 755 means rwxr-xr-x.

Raw data should never change, so many bioinformaticians make it read-only as soon as it arrives: chmod -R a-w data removes write permission from data and everything in it. Any later attempt to change or delete those files, by you or a buggy script, then fails with Permission denied. (As the owner you can always undo it with chmod -R u+w data.)

Interactive

Permissions explorer

Switch permissions on and off, or type a mode such as 750 or u+x, and see the ls -l string, the octal number and what each kind of user may do.

Practice terminal

Make the raw data read-only

learner@quanexas: ~
  1. Look at the permissions of the files in data/hbb with ls -l.

    Show the answer
    ls -l data/hbb
  2. Remove write permission for everyone from data and everything in it.

    Hint

    chmod with -R (recursive) and the mode a-w.

    Show the answer
    chmod -R a-w data
  3. Check the result with ls -l data/hbb again, then try rm data/hbb/P68871.fasta: it should refuse. (Run chmod -R u+w data if you ever need to change the data again.)

    Show the answer
    ls -l data/hbb

Check your understanding

Ten questions. Score 70% or more to complete this part of the topic. You can retake it as often as you like.

1In the command ls -lh data/lenski, what is data/lenski?
2You are in /home/learner/data/hbb. Which path points to /home/learner/data/lenski?
3What does cd with no arguments do?
4Which command makes results/qc and any missing parent directories, without an error if they already exist?
5A gzip-compressed FASTQ file gives 2,000,000 lines with zcat reads.fastq.gz | wc -l. How many reads does it contain?
6Which command shows a file from its second line on, skipping a header line?
7Which files does the pattern sample_?.fastq match?
8Why should you quote the pattern in find data -name '*.gz'?
9A file shows -rwxr-x--- in ls -l. What can members of its group do?
10What does chmod -R a-w data do?

Mini project: set up a reproducible project folder

Before any analysis, set up a project the way you would on a real server: a clear layout, the raw data copied in and protected, and a README explaining what is there. This terminal checks each step as you go.

Practice terminal

A project for the SARS-CoV-2 genome

learner@quanexas: ~
  1. Create the directories sars2/raw, sars2/results and sars2/docs in your home directory.

    Show the answer
    mkdir -p ~/sars2/{raw,results,docs}
  2. Copy the genome (NC_045512.2.fasta) and its annotation (NC_045512.2.gff3) from ~/data/sars-cov-2 into sars2/raw, with one command.

    Hint

    cp accepts several sources followed by one target directory. A wildcard such as NC_045512.2.{fasta,gff3} also works.

    Show the answer
    cp ~/data/sars-cov-2/NC_045512.2.fasta ~/data/sars-cov-2/NC_045512.2.gff3 ~/sars2/raw/
  3. Make everything in sars2/raw read-only.

    Show the answer
    chmod -R a-w ~/sars2/raw
  4. Write a sars2/README.md that says what the data are. Use nano sars2/README.md (type, then press Ctrl+O, Enter and Ctrl+X), or echo with >. Mention SARS-CoV-2.

    Hint

    echo "text" > file writes the text into a new file.

    Show the answer
    echo "SARS-CoV-2 reference genome NC_045512.2 (Wuhan-Hu-1) and its NCBI annotation, copied from ~/data/sars-cov-2." > ~/sars2/README.md
  5. Finally, look at the result with tree sars2, and at the permissions with ls -l sars2/raw.

    Show the answer
    tree sars2

Go further

  • Use ls -lh and wc -l to note the size and line count of each raw file in the README.
  • Make a checksum of the raw files with md5sum sars2/raw/* > sars2/docs/checksums.md5, and later confirm they are unchanged with md5sum -c.
  • Try to delete a raw file and read the error message: what would have happened without the read-only permissions?

Summary and further reading

Key takeaways

  • The shell runs programs from text commands: the program name, then options that change its behaviour, then arguments, usually files. --help, man and help explain any command.
  • Every command runs in a working directory. Absolute paths start at /; relative paths start where you are; ~ is home, . is here and .. is one level up.
  • Keep raw data, results and scripts apart. mkdir -p, cp, mv and rm build and rearrange projects, and rm has no undo.
  • Look at big files without opening them: head, tail, less and wc read them as a stream, and zcat does the same for gzip files.
  • Wildcards are expanded by the shell before a command runs; check them with echo or ls first. find searches a whole directory tree.
  • Permissions control who may read, write and execute. chmod -R a-w protects raw data from accidental changes.

Key terms

Data used on this page

References and further reading

  1. Brandies PA, Hogg CJ. Ten simple rules for getting started with command-line bioinformatics. PLOS Computational Biology 17, e1008645 (2021). doi:10.1371/journal.pcbi.1008645
  2. Noble WS. A quick guide to organizing computational biology projects. PLoS Computational Biology 5, e1000424 (2009). doi:10.1371/journal.pcbi.1000424
  3. Wilson G, et al. Good enough practices in scientific computing. PLOS Computational Biology 13, e1005510 (2017). doi:10.1371/journal.pcbi.1005510
  4. Wilson G, et al. Best practices for scientific computing. PLoS Biology 12, e1001745 (2014). doi:10.1371/journal.pbio.1001745
  5. Ritchie DM, Thompson K. The UNIX time-sharing system. Communications of the ACM 17, 365–375 (1974). doi:10.1145/361011.361061
  6. Cock PJA, Fields CJ, Goto N, Heuer ML, Rice PM. The Sanger FASTQ file format for sequences with quality scores, and the Solexa/Illumina FASTQ variants. Nucleic Acids Research 38, 1767–1771 (2010). doi:10.1093/nar/gkp1137
  7. Wu F, et al. A new coronavirus associated with human respiratory disease in China. Nature 579, 265–269 (2020). doi:10.1038/s41586-020-2008-3
  8. Tenaillon O, et al. Tempo and mode of genome evolution in a 50,000-generation experiment. Nature 536, 165–170 (2016). doi:10.1038/nature18959
  9. The Carpentries. The Unix Shell: a free lesson for researchers. swcarpentry.github.io
  10. GNU Bash Reference Manual. www.gnu.org
  11. GNU Coreutils manual: the core file, shell and text manipulation utilities. www.gnu.org

Finished the topic?

Pass the check and the exercises, or mark the topic complete yourself. Progress is saved in this browser.