{ "metadata": { "kernelspec": { "display_name": "Bash", "language": "bash", "name": "bash" }, "language_info": { "codemirror_mode": "shell", "file_extension": ".sh", "mimetype": "text/x-sh", "name": "bash" } }, "nbformat": 4, "nbformat_minor": 5, "cells": [ { "id": "metadata", "cell_type": "markdown", "source": "
\n\n# CLI basics\n\nby [The Carpentries](https://training.galaxyproject.org/hall-of-fame/carpentries/), [Helena Rasche](https://training.galaxyproject.org/hall-of-fame/hexylena/), [Bazante Sanders](https://training.galaxyproject.org/hall-of-fame/bazante1/), [Erasmus+ Programme](https://training.galaxyproject.org/hall-of-fame/erasmusplus/), [Avans Hogeschool](https://training.galaxyproject.org/hall-of-fame/avans-atgm/)\n\nCC-BY licensed content from the [Galaxy Training Network](https://training.galaxyproject.org/)\n\n**Objectives**\n\n- What is a command shell and why would I use one?\n- How can I move around on my computer?\n- How can I see what files and directories I have?\n- How can I specify the location of a file or directory on my computer?\n- How can I create, copy, and delete files and directories?\n- How can I edit files?\n\n**Objectives**\n\n- Explain how the shell relates to the keyboard, the screen, the operating system, and users' programs.\n- Explain when and why command-line interfaces should be used instead of graphical interfaces.\n- Explain the similarities and differences between a file and a directory.\n- Translate an absolute path into a relative path and vice versa.\n- Construct absolute and relative paths that identify specific files and directories.\n- Use options and arguments to change the behaviour of a shell command.\n- Demonstrate the use of tab completion and explain its advantages.\n- Create a directory hierarchy that matches a given diagram.\n- Create files in that hierarchy using an editor or by copying and renaming existing files.\n- Delete, copy and move specified files and/or directories.\n\n**Time Estimation: 1H**\n
\n", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-0", "source": "

This tutorial will walk you through the basics of how to use the Unix command line.

\n
\n

💬 Comment

\n

This tutorial is significantly based on the Carpentries “The Unix Shell” lesson, which is licensed CC-BY 4.0. Adaptations have been made to make this work better in a GTN/Galaxy environment.

\n
\n
\n

Agenda

\n

In this tutorial, we will cover:

\n
    \n
  1. Background
      \n
    1. Setup
    2. \n
    \n
  2. \n
\n
\n

Background

\n

Humans and computers commonly interact in many different ways, such as through a keyboard and mouse,\ntouch screen interfaces, or using speech recognition systems.\nThe most widely used way to interact with personal computers is called a\ngraphical user interface (GUI).\nWith a GUI, we give instructions by clicking a mouse and using menu-driven interactions.

\n

While the visual aid of a GUI makes it intuitive to learn,\nthis way of delivering instructions to a computer scales very poorly.\nImagine the following task:\nfor a literature search, you have to copy the third line of one thousand text files in one thousand\ndifferent directories and paste it into a single file.\nUsing a GUI, you would not only be clicking at your desk for several hours,\nbut you could potentially also commit an error in the process of completing this repetitive task.\nThis is where we take advantage of the Unix shell.\nThe Unix shell is both a command-line interface (CLI) and a scripting language,\nallowing such repetitive tasks to be done automatically and fast.\nWith the proper commands, the shell can repeat tasks with or without some modification\nas many times as we want.\nUsing the shell, the task in the literature example can be accomplished in seconds.

\n

Setup

\n

Before we do anything, we’ll get you setup with some test data which can help\nguide your exploration of the CLI.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-1", "source": [ "cd ~/\n", "mkdir -p Desktop/\n", "cd Desktop/\n", "wget -c https://github.com/swcarpentry/shell-novice/raw/2929ba2cbb1bcb5ff0d1b4100c6e58b96e155fd1/data/shell-lesson-data.zip\n", "unzip -u shell-lesson-data.zip" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-2", "source": "

The Shell

\n

The shell is a program where users can type commands.\nWith the shell, it’s possible to invoke complicated programs like climate modeling software\nor simple commands that create an empty directory with only one line of code.\nThe most popular Unix shell is Bash (the Bourne Again SHell —\nso-called because it’s derived from a shell written by Stephen Bourne).\nBash is the default shell on most modern implementations of Unix and in most packages that provide\nUnix-like tools for Windows.

\n

Using the shell will take some effort and some time to learn.\nWhile a GUI presents you with choices to select, CLI choices are not automatically presented to you,\nso you must learn a few commands like new vocabulary in a language you’re studying.\nHowever, unlike a spoken language, a small number of “words” (i.e. commands) gets you a long way,\nand we’ll cover those essential few today.

\n

The grammar of a shell allows you to combine existing tools into powerful\npipelines and handle large volumes of data automatically. Sequences of\ncommands can be written into a script, improving the reproducibility of\nworkflows.

\n

In addition, the command line is often the easiest way to interact with remote machines\nand supercomputers.\nFamiliarity with the shell is near essential to run a variety of specialized tools and resources\nincluding high-performance computing systems.\nAs clusters and cloud computing systems become more popular for scientific data crunching,\nbeing able to interact with the shell is becoming a necessary skill.\nWe can build on the command-line skills covered here\nto tackle a wide range of scientific questions and computational challenges.

\n

Let’s get started.

\n

When the shell is first opened, you are presented with a prompt,\nindicating that the shell is waiting for input.

\n
$\n
\n

The shell typically uses $ as the prompt, but may use a different symbol.\nIn the examples for this lesson, we will not include this prompt!

\n

Most importantly:\nwhen typing commands, either from these lessons or from other sources,\ndo not type the prompt, only the commands that follow it.\nAlso note that after you type a command, you have to press the Enter key to execute it.

\n

The prompt is followed by a text cursor, a character that indicates the position where your\ntyping will appear.\nThe cursor is usually a flashing or solid block, but it can also be an underscore or a pipe.\nYou may have seen it in a text editor program, for example.

\n

So let’s try our first command, ls which is short for listing.

\n
\n

✏️ Open a Jupyter Terminal

\n

This tutorial will let you accomplish almost everything from this view, running code in the cells below directly in the training material. You can choose between running the code here, or opening up a terminal tab in which to run it.

\n

Here are some instructions for how to do this on various environments.

\n

Jupyter on UseGalaxy.* and MyBinder.org

\n
    \n
  1. \n

    Use the File → New → Terminal menu to launch a terminal.

    \n

    \"screenshot

    \n
  2. \n
  3. \n

    Disable “Simple” mode in the bottom left hand corner, if it activated.

    \n

    \"screenshot

    \n
  4. \n
  5. \n

    Drag one of the terminal or notebook tabs to the side to have the training materials and terminal side-by-side

    \n

    \"screenshot

    \n
  6. \n
\n

CoCalc

\n
    \n
  1. \n

    Use the Split View functionality of cocalc to split your view into two portions.

    \n

    \"screenshot

    \n
  2. \n
  3. \n

    Change the view of one panel to a terminal

    \n

    \"screenshot

    \n
  4. \n
\n
\n

This command will list the contents of the current directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-3", "source": [ "ls" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-4", "source": "
\n

💡 Command not found

\n

If the shell can’t find a program whose name is the command you typed, it\nwill print an error message such as:

\n
\n

⌨️ Input: Bash

\n
$ ks\n
\n
\n
\n

🖥 Output

\n
ks: command not found\n
\n
\n

This might happen if the command was mis-typed or if the program corresponding to that command\nis not installed.

\n
\n

Nelle’s Pipeline: A Typical Problem

\n

Nelle Nemo, a marine biologist,\nhas just returned from a six-month survey of the\nNorth Pacific Gyre,\nwhere she has been sampling gelatinous marine life in the\nGreat Pacific Garbage Patch.\nShe has 1520 samples that she’s run through an assay machine to measure the relative abundance\nof 300 proteins.\nShe needs to run these 1520 files through an imaginary program called goostats.sh she inherited.\nOn top of this huge task, she has to write up results by the end of the month so her paper\ncan appear in a special issue of Aquatic Goo Letters.

\n

The bad news is that if she has to run goostats.sh by hand using a GUI,\nshe’ll have to select and open a file 1520 times.\nIf goostats.sh takes 30 seconds to run each file, the whole process will take more than 12 hours\nof Nelle’s attention.\nWith the shell, Nelle can instead assign her computer this mundane task while she focuses\nher attention on writing her paper.

\n

The next few lessons will explore the ways Nelle can achieve this.\nMore specifically,\nthey explain how she can use a command shell to run the goostats.sh program,\nusing loops to automate the repetitive steps of entering file names,\nso that her computer can work while she writes her paper.

\n

As a bonus,\nonce she has put a processing pipeline together,\nshe will be able to use it again whenever she collects more data.

\n

In order to achieve her task, Nelle needs to know how to:

\n\n

Navigating Files and Directories

\n

The part of the operating system responsible for managing files and directories\nis called the file system.\nIt organizes our data into files,\nwhich hold information,\nand directories (also called ‘folders’),\nwhich hold files or other directories.

\n

Several commands are frequently used to create, inspect, rename, and delete files and directories.\nTo start exploring them, we’ll go to our open shell window.

\n

First, let’s find out where we are by running a command called pwd\n(which stands for ‘print working directory’). Directories are like places, at any time\nwhile we are using the shell, we are in exactly one place called\nour current working directory. Commands mostly read and write files in the\ncurrent working directory, i.e. ‘here’, so knowing where you are before running\na command is important. pwd shows you where you are:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-5", "source": [ "pwd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-6", "source": "

Try running it now.

\n
\n

💡 Home Directory Variation

\n

The home directory path will look different on different operating systems.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
LinuxOSXJupyter (UseGalaxy/Binder)CoCalc
/home/nelle/Users/nelle/home/joyvan/projects/</code>
\n

On Windows, it will be similar to C:\\Documents and Settings\\nelle or C:\\Users\\nelle.\n(Note that it may look slightly different for different versions of Windows.)\nIn future examples, we’ve used Mac output as the default - Linux and Windows\noutput may differ slightly but should be generally similar.

\n

We will also assume that your pwd command returns your user’s home directory.\nIf pwd returns something different, you may need to navigate there using cd\nor some commands in this lesson will not work as written.\nSee Exploring Other Directories for more details\non the cd command.

\n
\n

To understand what a ‘home directory’ is,\nlet’s have a look at how the file system as a whole is organized. For the\nsake of this example, we’ll be\nillustrating the filesystem on our scientist Nelle’s computer. After this\nillustration, you’ll be learning commands to explore your own filesystem,\nwhich will be constructed in a similar way, but not be exactly identical.

\n

On Nelle’s computer, the filesystem looks like this:

\n

\"The

\n

At the top is the root directory\nthat holds everything else.\nWe refer to it using a slash character, /, on its own;\nthis character is the leading slash in /Users/nelle.

\n

Inside that directory are several other directories:\nbin (which is where some built-in programs are stored),\ndata (for miscellaneous data files),\nUsers (where users’ personal directories are located),\ntmp (for temporary files that don’t need to be stored long-term),\nand so on.

\n

We know that our current working directory /Users/nelle is stored inside /Users\nbecause /Users is the first part of its name.\nSimilarly,\nwe know that /Users is stored inside the root directory /\nbecause its name begins with /.

\n
\n

Slashes

\n

Notice that there are two meanings for the / character.\nWhen it appears at the front of a file or directory name,\nit refers to the root directory. When it appears inside a path,\nit’s just a separator.

\n
\n

Underneath /Users,\nwe find one directory for each user with an account on Nelle’s machine,\nher colleagues imhotep and larry.

\n

\"Like

\n

The user imhotep’s files are stored in /Users/imhotep,\nuser larry’s in /Users/larry,\nand Nelle’s in /Users/nelle. Because Nelle is the user in our\nexamples here, therefore we get /Users/nelle as our home directory.\nTypically, when you open a new command prompt, you will be in\nyour home directory to start.

\n

Now let’s learn the command that will let us see the contents of our\nown filesystem. We can see what’s in our home directory by running ls:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-7", "source": [ "ls" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-8", "source": "

ls prints the names of the files and directories in the current directory.\nWe can make its output more comprehensible by using the -F option\n(also known as a switch or a flag),\nwhich tells ls to classify the output\nby adding a marker to file and directory names to indicate what they are:

\n\n

Depending on your default options,\nthe shell might also use colors to indicate whether each entry is a file or\ndirectory.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-9", "source": [ "ls -F" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-10", "source": "

Here,\nwe can see that our home directory contains only sub-directories.\nAny names in our output that don’t have a classification symbol\nare plain old files.

\n
\n

💡 Real Terminal Tip: Clearing your terminal

\n

If your screen gets too cluttered, you can clear your terminal using the\nclear command. You can still access previous commands using \nand to move line-by-line, or by scrolling in your terminal.

\n
\n

Getting help

\n

ls has lots of other options. There are two common ways to find out how\nto use a command and what options it accepts:

\n
    \n
  1. We can pass a --help option to the command,
  2. \n
  3. We can read its manual with man
  4. \n
\n

The --help option

\n

Many bash commands, and programs that people have written that can be\nrun from within bash, support a --help option to display more\ninformation on how to use the command or program.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-11", "source": [ "ls --help" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-12", "source": "
\n

💡 Unsupported command-line options

\n

If you try to use an option (flag) that is not supported, ls and other commands\nwill usually print an error message similar to:

\n
\n

⌨️ Input: Bash

\n
ls -j\n
\n
\n
\n

🖥 Output

\n
ls: invalid option -- 'j'\nTry 'ls --help' for more information.\n
\n
\n
\n

The man command

\n

The other way to learn about ls is to type

\n
\n

⌨️ Input: Bash

\n
$ man ls\n
\n
\n
\n

🖥 Output

\n
LS(1)                                                          User Commands                                                          LS(1)\n\nNAME\n       ls - list directory contents\n\nSYNOPSIS\n       ls [OPTION]... [FILE]...\n\nDESCRIPTION\n       List information about the FILEs (the current directory by default).  Sort entries alphabetically if none of -cftuvSUX nor --sort is\n       specified.\n\n       Mandatory arguments to long options are mandatory for short options too.\n\n       -a, --all\n              do not ignore entries starting with .\n\n       -A, --almost-all\n              do not list implied . and ..\n\n       --author\n              with -l, print the author of each file\n\n       -b, --escape\n              print C-style escapes for nongraphic characters\n\n       --block-size=SIZE\n              with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see SIZE format below\n\n       -B, --ignore-backups\n              do not list implied entries ending with ~\n\n       -c     with -lt: sort by, and show, ctime (time of last modification of file status information); with -l: show ctime  and  sort  by\n              name; otherwise: sort by ctime, newest first\n\n       -C     list entries by columns\n\n       --color[=WHEN]\n              colorize the output; WHEN can be 'always' (default if omitted), 'auto', or 'never'; more info below\n
\n
\n

This command will turn your terminal into a page with a description\nof the ls command and its options.

\n

To navigate through the man pages,\nyou may use and to move line-by-line,\nor try B and Spacebar to skip up and down by a full page.\nTo search for a character or word in the man pages,\nuse / followed by the character or word you are searching for.\nSometimes a search will result in multiple hits.\nIf so, you can move between hits using N (for moving forward) and\nShift+N (for moving backward).

\n

To quit the man pages, press Q.

\n
\n

💡 Manual pages on the web

\n

Of course, there is a third way to access help for commands:\nsearching the internet via your web browser.\nWhen using internet search, including the phrase unix man page in your search\nquery will help to find relevant results.

\n

GNU provides links to its\nmanuals including the\ncore GNU utilities,\nwhich covers many commands introduced within this lesson.

\n
\n
\n

❓ Exploring More ls Flags

\n

You can also use two options at the same time. What does the command ls do when used\nwith the -l option? What about if you use both the -l and the -h option?

\n

Some of its output is about properties that we do not cover in this lesson (such\nas file permissions and ownership), but the rest should be useful\nnevertheless.

\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n

The -l option makes ls use a long listing format, showing not only\nthe file/directory names but also additional information, such as the file size\nand the time of its last modification. If you use both the -h option and the -l option,\nthis makes the file size ‘human readable’, i.e. displaying something like 5.3K\ninstead of 5369.

\n
\n
\n
\n

❓ Listing in Reverse Chronological Order

\n

By default, ls lists the contents of a directory in alphabetical\norder by name. The command ls -t lists items by time of last\nchange instead of alphabetically. The command ls -r lists the\ncontents of a directory in reverse order.\nWhich file is displayed last when you combine the -t and -r flags?\nHint: You may need to use the -l flag to see the\nlast changed dates.

\n
\n

👁 Solution

\n

The most recently changed file is listed last when using -rt. This\ncan be very useful for finding your most recent edits or checking to\nsee if a new output file was written.

\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-13", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-14", "source": "

Exploring Other Directories

\n

Not only can we use ls on the current working directory,\nbut we can use it to list the contents of a different directory.\nLet’s take a look at our current directory by running ls -F ~/,\ni.e.,\nthe command ls with the -F option and the [argument][Arguments] /.\nThe argument ~/ tells ls that\nwe want a listing of something other than our current working directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-15", "source": [ "ls -F ~/" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-16", "source": "

As you may now see, using a bash shell is strongly dependent on the idea that\nyour files are organized in a hierarchical file system.\nOrganizing things hierarchically in this way helps us keep track of our work:\nit’s possible to put hundreds of files in our home directory,\njust as it’s possible to pile hundreds of printed papers on our desk,\nbut it’s a self-defeating strategy.

\n

Now that we know the shell-lesson-data directory is located in current working directory, we\ncan do two things.

\n

First, we can look at its contents, using the same strategy as before, passing\na directory name to ls:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-17", "source": [ "ls -F shell-lesson-data" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-18", "source": "

Second, we can actually change our location to a different directory, so\nwe are no longer located in\nour home directory.

\n

The command to change locations is cd followed by a\ndirectory name to change our working directory.\ncd stands for ‘change directory’,\nwhich is a bit misleading:\nthe command doesn’t change the directory;\nit changes the shell’s idea of what directory we are in.\nThe cd command is akin to double clicking a folder in a graphical interface to get into a folder.

\n

Let’s say we want to move to the data directory we saw above. We can\nuse the following series of commands to get there:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-19", "source": [ "cd shell-lesson-data" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-20", "source": "

These commands will move us into\nthe shell-lesson-data directory, then into the data directory.\nYou will notice that cd doesn’t print anything. This is normal.\nMany shell commands will not output anything to the screen when successfully executed.\nBut if we run pwd after it, we can see that we are now\nin /Users/nelle/Desktop/shell-lesson-data/data.\nIf we run ls -F without arguments now,\nit lists the contents of /Users/nelle/Desktop/shell-lesson-data/data,\nbecause that’s where we now are:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-21", "source": [ "pwd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-22", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-23", "source": [ "ls -F data/" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-24", "source": "

We now know how to go down the directory tree (i.e. how to go into a subdirectory),\nbut how do we go up (i.e. how do we leave a directory and go into its parent directory)?\nWe might try the following:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-25", "source": [ "cd shell-lesson-data" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-26", "source": "

But we get an error! Why is this?

\n

With our methods so far,\ncd can only see sub-directories inside your current directory. There are\ndifferent ways to see directories above your current location; we’ll start\nwith the simplest.

\n

There is a shortcut in the shell to move up one directory level\nthat looks like this:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-27", "source": [ "cd .." ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-28", "source": "

.. is a special directory name meaning\n“the directory containing this one”,\nor more succinctly,\nthe parent of the current directory.\nSure enough,\nif we run pwd after running cd .., we’re back in /Users/nelle/Desktop/shell-lesson-data:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-29", "source": [ "pwd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-30", "source": "

The special directory .. doesn’t usually show up when we run ls. If we want\nto display it, we can add the -a option to ls -F:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-31", "source": [ "ls -F -a" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-32", "source": "

-a stands for ‘show all’;\nit forces ls to show us file and directory names that begin with .,\nsuch as .. (which, if we’re in /Users/nelle, refers to the /Users directory).\nAs you can see,\nit also displays another special directory that’s just called .,\nwhich means ‘the current working directory’.\nIt may seem redundant to have a name for it,\nbut we’ll see some uses for it soon.

\n

Note that in most command line tools, multiple options can be combined\nwith a single - and no spaces between the options: ls -F -a is\nequivalent to ls -Fa.

\n
\n

💡 Other Hidden Files

\n

In addition to the hidden directories .. and ., you may also see a file\ncalled .bash_profile. This file usually contains shell configuration\nsettings. You may also see other files and directories beginning\nwith .. These are usually files and directories that are used to configure\ndifferent programs on your computer. The prefix . is used to prevent these\nconfiguration files from cluttering the terminal when a standard ls command\nis used.

\n
\n

These three commands are the basic commands for navigating the filesystem on your computer:\npwd, ls, and cd. Let’s explore some variations on those commands. What happens\nif you type cd on its own, without giving\na directory?

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-33", "source": [ "cd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-34", "source": "

How can you check what happened? pwd gives us the answer!

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-35", "source": [ "pwd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-36", "source": "

It turns out that cd without an argument will return you to your home directory,\nwhich is great if you’ve gotten lost in your own filesystem.

\n

Let’s try returning to the data directory from before. Last time, we used\nthree commands, but we can actually string together the list of directories\nto move to data in one step:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-37", "source": [ "cd ~/Desktop/shell-lesson-data/data" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-38", "source": "

Check that we’ve moved to the right place by running pwd and ls -F.

\n

If we want to move up one level from the data directory, we could use cd ... But\nthere is another way to move to any directory, regardless of your\ncurrent location.

\n

So far, when specifying directory names, or even a directory path (as above),\nwe have been using relative paths. When you use a relative path with a command\nlike ls or cd, it tries to find that location from where we are,\nrather than from the root of the file system.

\n

However, it is possible to specify the absolute path to a directory by\nincluding its entire path from the root directory, which is indicated by a\nleading slash. The leading / tells the computer to follow the path from\nthe root of the file system, so it always refers to exactly one directory,\nno matter where we are when we run the command.

\n

This allows us to move to our shell-lesson-data directory from anywhere on\nthe filesystem (including from inside data). To find the absolute path\nwe’re looking for, we can use pwd and then extract the piece we need\nto move to shell-lesson-data.

\n
\n

⌨️ Input: Bash

\n
$ pwd\n
\n
\n
\n

🖥 Output

\n
/Users/nelle/\n
\n
\n

Then we could run something like:

\n
$ cd /Users/nelle/shell-lesson-data\n
\n

Run pwd and ls -F to ensure that we’re in the directory we expect. If we’re not, edit the command block below to make sure we’re in the correct location (~/Desktop/shell-lesson-data/)

\n
pwd\nls -F\n
\n
\n

💡 Two More Shortcuts

\n

The shell interprets a tilde (~) character at the start of a path to\nmean “the current user’s home directory”. For example, if Nelle’s home\ndirectory is /Users/nelle, then ~/data is equivalent to\n/Users/nelle/data. This only works if it is the first character in the\npath: here/there/~/elsewhere is not here/there/Users/nelle/elsewhere.

\n

Another shortcut is the - (dash) character. cd will translate - into\nthe previous directory I was in, which is faster than having to remember,\nthen type, the full path. This is a very efficient way of moving\nback and forth between two directories – i.e. if you execute cd - twice,\nyou end up back in the starting directory.

\n

The difference between cd .. and cd - is\nthat the former brings you up, while the latter brings you back.

\n
\n

Try it out below!

\n
\n

First navigate to ~/Desktop/shell-lesson-data (you should already be there).

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-39", "source": [ "cd ~/Desktop/shell-lesson-data" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-40", "source": "

Then cd into the creatures directory

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-41", "source": [ "cd creatures" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-42", "source": "

Now if you run

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-43", "source": [ "cd -" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-44", "source": "

you’ll see you’re back in ~/Desktop/shell-lesson-data.\nRun cd - again and you’re back in ~/Desktop/shell-lesson-data/creatures

\n
\n

❓ Absolute vs Relative Paths

\n

Starting from /Users/amanda/data,\nwhich of the following commands could Amanda use to navigate to her home directory,\nwhich is /Users/amanda?

\n
    \n
  1. cd .
  2. \n
  3. cd /
  4. \n
  5. cd /home/amanda
  6. \n
  7. cd ../..
  8. \n
  9. cd ~
  10. \n
  11. cd home
  12. \n
  13. cd ~/data/..
  14. \n
  15. cd
  16. \n
  17. cd ..
  18. \n
\n
\n

❓ Solution

\n
    \n
  1. No: . stands for the current directory.
  2. \n
  3. No: / stands for the root directory.
  4. \n
  5. No: Amanda’s home directory is /Users/amanda.
  6. \n
  7. No: this command goes up two levels, i.e. ends in /Users.
  8. \n
  9. Yes: ~ stands for the user’s home directory, in this case /Users/amanda.
  10. \n
  11. No: this command would navigate into a directory home in the current directory, if it exists.
  12. \n
  13. Yes: unnecessarily complicated, but correct.
  14. \n
  15. Yes: shortcut to go back to the user’s home directory.
  16. \n
  17. Yes: goes up one level.
  18. \n
\n
\n
\n
\n

❓ Relative Path Resolution

\n

Using the filesystem diagram below, if pwd displays /Users/thing,\nwhat will ls -F ../backup display?

\n
    \n
  1. ../backup: No such file or directory
  2. \n
  3. 2012-12-01 2013-01-08 2013-01-27
  4. \n
  5. 2012-12-01/ 2013-01-08/ 2013-01-27/
  6. \n
  7. original/ pnas_final/ pnas_sub/
  8. \n
\n

\"A

\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
    \n
  1. No: there is a directory backup in /Users.
  2. \n
  3. No: this is the content of Users/thing/backup, but with .., we asked for one level further up.
  4. \n
  5. No: see previous explanation.
  6. \n
  7. Yes: ../backup/ refers to /Users/backup/.
  8. \n
\n
\n
\n
\n

ls Reading Comprehension

\n

Using the filesystem diagram below,\nif pwd displays /Users/backup,\nand -r tells ls to display things in reverse order,\nwhat command(s) will result in the following output:

\n
pnas_sub/ pnas_final/ original/\n
\n

\"A

\n
    \n
  1. ls pwd
  2. \n
  3. ls -r -F
  4. \n
  5. ls -r -F /Users/backup
  6. \n
\n
\n

👁 Solution

\n
    \n
  1. No: pwd is not the name of a directory.
  2. \n
  3. Yes: ls without directory argument lists files and directories in the current directory.
  4. \n
  5. Yes: uses the absolute path explicitly.
  6. \n
\n
\n
\n

General Syntax of a Shell Command

\n

We have now encountered commands, options, and arguments,\nbut it is perhaps useful to formalise some terminology.

\n

Consider the command below as a general example of a command,\nwhich we will dissect into its component parts:

\n
$ ls -F ~/Desktop/shell-lesson-data/\n
\n

ls is the command, with an option -F and an\nargument /.\nWe’ve already encountered options (also called switches or flags) which\neither start with a single dash (-) or two dashes (--),\nand they change the behavior of a command.\n[Arguments] tell the command what to operate on (e.g. files and directories).\nSometimes options and arguments are referred to as parameters.\nA command can be called with more than one option and more than one argument, but a\ncommand doesn’t always require an argument or an option.

\n

Each part is separated by spaces: if you omit the space\nbetween ls and -F the shell will look for a command called ls-F, which\ndoesn’t exist. Also, capitalization can be important.\nFor example, ls -s will display the size of files and directories alongside the names,\nwhile ls -S will sort the files and directories by size, as shown below:

\n
$ ls -s Desktop/shell-lesson-data/data\ntotal 116\n 4 amino-acids.txt   4 animals.txt   4 morse.txt  12 planets.txt  76 sunspot.txt\n 4 animal-counts     4 elements      4 pdb         4 salmon.txt\n$ ls -S Desktop/shell-lesson-data/data\nsunspot.txt  animal-counts  pdb        amino-acids.txt  salmon.txt\nplanets.txt  elements       morse.txt  animals.txt\n
\n

Putting all that together, our command above gives us a listing\nof files and directories in our shell-lesson-data folder.

\n

Nelle’s Pipeline: Organizing Files

\n

Knowing this much about files and directories,\nNelle is ready to organize the files that the protein assay machine will create.\nFirst,\nshe creates a directory called north-pacific-gyre\n(to remind herself where the data came from).\nInside that,\nshe creates a directory called 2012-07-03,\nwhich is the date she started processing the samples.\nShe used to use names like conference-paper and revised-results,\nbut she found them hard to understand after a couple of years.\n(The final straw was when she found herself creating\na directory called revised-revised-results-3.)

\n
\n

💡 Sorting Output

\n

Nelle names her directories ‘year-month-day’,\nwith leading zeroes for months and days,\nbecause the shell displays file and directory names in alphabetical order.\nIf she used month names,\nDecember would come before July;\nif she didn’t use leading zeroes,\nNovember (‘11’) would come before July (‘7’). Similarly, putting the year first\nmeans that June 2012 will come before June 2013.

\n
\n

Each of her physical samples is labelled according to her lab’s convention\nwith a unique ten-character ID,\nsuch as ‘NENE01729A’.\nThis ID is what she used in her collection log\nto record the location, time, depth, and other characteristics of the sample,\nso she decides to use it as part of each data file’s name.\nSince the assay machine’s output is plain text,\nshe will call her files NENE01729A.txt, NENE01812A.txt, and so on.\nAll 1520 files will go into the same directory.

\n

Now in her current directory shell-lesson-data,\nNelle can see what files she has using the command:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-45", "source": [ "ls north-pacific-gyre/2012-07-03/" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-46", "source": "

This command is a lot to type,\nbut she can let the shell do most of the work through what is called tab completion.\nIf she types:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-47", "source": [ "ls nor" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-48", "source": "

and then presses Tab (the tab key on her keyboard),\nthe shell automatically completes the directory name for her:

\n
$ ls north-pacific-gyre/\n
\n

If she presses Tab again,\nBash will add 2012-07-03/ to the command,\nsince it’s the only possible completion.\nPressing Tab again does nothing,\nsince there are 19 possibilities;\npressing Tab twice brings up a list of all the files,\nand so on.\nThis is called tab completion,\nand we will see it in many other tools as we go on.

\n

Working with Files and Directories

\n

We now know how to explore files and directories,\nbut how do we create them in the first place?

\n

Step one: see where we are and what we already have

\n

Let’s go back to our shell-lesson-data directory on the Desktop\nand use ls -F to see what it contains:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-49", "source": [ "pwd" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-50", "source": "\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-51", "source": [ "ls -F" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-52", "source": "

You should see folders like the following, if not, you’re in the wrong place!

\n
creatures/  data/  molecules/  north-pacific-gyre/  notes.txt  pizza.cfg  solar.pdf  writing/\n
\n

Create a directory

\n

Let’s create a new directory called thesis using the command mkdir thesis\n(which has no output):

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-53", "source": [ "mkdir thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-54", "source": "

As you might guess from its name,\nmkdir means ‘make directory’.\nSince thesis is a relative path\n(i.e., does not have a leading slash, like /what/ever/thesis),\nthe new directory is created in the current working directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-55", "source": [ "ls -F" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-56", "source": "

Since we’ve just created the thesis directory, there’s nothing in it yet:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-57", "source": [ "ls -F thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-58", "source": "

Note that mkdir is not limited to creating single directories one at a time.\nThe -p option allows mkdir to create a directory with nested subdirectories\nin a single operation:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-59", "source": [ "mkdir -p project/data project/results" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-60", "source": "

The -R option to the ls command will list all nested subdirectories within a directory.\nLet’s use ls -FR to recursively list the new directory hierarchy we just created in the\nproject directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-61", "source": [ "ls -FR project" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-62", "source": "

It should look like:

\n
project/:\ndata/  results/\n\nproject/data:\n\nproject/results:\n
\n
\n

💡 Two ways of doing the same thing

\n

Using the shell to create a directory is no different than using a file explorer.\nIf you open the current directory using your operating system’s graphical file explorer,\nthe thesis directory will appear there too.\nWhile the shell and the file explorer are two different ways of interacting with the files,\nthe files and directories themselves are the same.

\n
\n
\n

💡 Good names for files and directories

\n

Complicated names of files and directories can make your life painful\nwhen working on the command line. Here we provide a few useful\ntips for the names of your files and directories.

\n
    \n
  1. \n

    Don’t use spaces.

    \n

    Spaces can make a name more meaningful,\nbut since spaces are used to separate arguments on the command line\nit is better to avoid them in names of files and directories.\nYou can use - or _ instead (e.g. north-pacific-gyre/ rather than north pacific gyre/).\nTo test this out, try typing mkdir north pacific gyreand see what directory (or directories!)\nare made when you check with ls -F.

    \n
  2. \n
  3. \n

    Don’t begin the name with - (dash).

    \n

    Commands treat names starting with - as options.

    \n
  4. \n
  5. \n

    Stick with letters, numbers, . (period or ‘full stop’), - (dash) and _ (underscore).

    \n

    Many other characters have special meanings on the command line.\nWe will learn about some of these during this lesson.\nThere are special characters that can cause your command to not work as\nexpected and can even result in data loss.

    \n
  6. \n
\n

If you need to refer to names of files or directories that have spaces\nor other special characters, you should surround the name in quotes (\"\").

\n
\n

Creating a text file

\n

Let’s change our working directory to thesis using cd,\nthen run a text editor called Nano to create a file called draft.txt:

\n
$ cd thesis\n$ nano draft.txt\n
\n
\n

⚠️ Nano won’t work in a Jupyter Notebook!

\n

Nano is an interactive, full screen editor. You’ll need to switch to a proper\nconsole to do this step, if you haven’t already.

\n

In JupyterLab you can find this under the top menu by clicking File -> New -> Terminal

\n
\n
\n

💡 Which Editor?

\n

When we say, “nano is a text editor” we really do mean “text”: it can\nonly work with plain character data, not tables, images, or any other\nhuman-friendly media. We use it in examples because it is one of the\nleast complex text editors. However, because of this trait, it may\nnot be powerful enough or flexible enough for the work you need to do\nafter this workshop. On Unix systems (such as Linux and macOS),\nmany programmers use Emacs or\nVim (both of which require more time to learn),\nor a graphical editor such as\nGedit. On Windows, you may wish to\nuse Notepad++. Windows also has a built-in\neditor called notepad that can be run from the command line in the same\nway as nano for the purposes of this lesson.

\n

No matter what editor you use, you will need to know where it searches\nfor and saves files. If you start it from the shell, it will (probably)\nuse your current working directory as its default location. If you use\nyour computer’s start menu, it may want to save files in your desktop or\ndocuments directory instead. You can change this by navigating to\nanother directory the first time you “Save As…”

\n
\n

Let’s type in a few lines of text.\nOnce we’re happy with our text, we can press Ctrl+O\n(press the Ctrl or Control key and, while\nholding it down, press the O key) to write our data to disk\n(we’ll be asked what file we want to save this to:\npress Return to accept the suggested default of draft.txt).

\n

\"screenshot

\n

Once our file is saved, we can use Ctrl+X to quit the editor and\nreturn to the shell.

\n
\n

💡 Control, Ctrl, or ^ Key

\n

The Control key is also called the ‘Ctrl’ key. There are various ways\nin which using the Control key may be described. For example, you may\nsee an instruction to press the Control key and, while holding it down,\npress the X key, described as any of:

\n\n

In nano, along the bottom of the screen you’ll see ^G Get Help ^O WriteOut.\nThis means that you can use Control-G to get help and Control-O to save your\nfile.

\n
\n

nano doesn’t leave any output on the screen after it exits,\nbut ls now shows that we have created a file called draft.txt:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-63", "source": [ "ls" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-64", "source": "
\n

❓ Creating Files a Different Way

\n

We have seen how to create text files using the nano editor.\nNow, try the following command:

\n
touch my_file.txt\n
\n
    \n
  1. \n

    What did the touch command do?\nWhen you look at your current directory using the GUI file explorer,\ndoes the file show up?

    \n
  2. \n
  3. \n

    Use ls -l to inspect the files. How large is my_file.txt?

    \n
  4. \n
  5. \n

    When might you want to create a file this way?

    \n
  6. \n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
    \n
  1. \n

    The touch command generates a new file called my_file.txt in\nyour current directory. You\ncan observe this newly generated file by typing ls at the\ncommand line prompt. my_file.txt can also be viewed in your\nGUI file explorer.

    \n
  2. \n
  3. \n

    When you inspect the file with ls -l, note that the size of\nmy_file.txt is 0 bytes. In other words, it contains no data.\nIf you open my_file.txt using your text editor it is blank.

    \n
  4. \n
  5. \n

    Some programs do not generate output files themselves, but\ninstead require that empty files have already been generated.\nWhen the program is run, it searches for an existing file to\npopulate with its output. The touch command allows you to\nefficiently generate a blank text file to be used by such\nprograms.

    \n
  6. \n
\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-65", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-66", "source": "
\n

💡 What’s In A Name?

\n

You may have noticed that all of Nelle’s files are named ‘something dot\nsomething’, and in this part of the lesson, we always used the extension\n.txt. This is just a convention: we can call a file mythesis or\nalmost anything else we want. However, most people use two-part names\nmost of the time to help them (and their programs) tell different kinds\nof files apart. The second part of such a name is called the\nfilename extension and indicates\nwhat type of data the file holds: .txt signals a plain text file, .pdf\nindicates a PDF document, .cfg is a configuration file full of parameters\nfor some program or other, .png is a PNG image, and so on.

\n

This is just a convention, albeit an important one. Files contain\nbytes: it’s up to us and our programs to interpret those bytes\naccording to the rules for plain text files, PDF documents, configuration\nfiles, images, and so on.

\n

Naming a PNG image of a whale as whale.mp3 doesn’t somehow\nmagically turn it into a recording of whale song, though it might\ncause the operating system to try to open it with a music player\nwhen someone double-clicks it.

\n
\n

Moving files and directories

\n

Returning to the shell-lesson-data directory,

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-67", "source": [ "cd ~/Desktop/shell-lesson-data/" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-68", "source": "

In our thesis directory we have a file draft.txt\nwhich isn’t a particularly informative name,\nso let’s change the file’s name using mv,\nwhich is short for ‘move’:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-69", "source": [ "mv thesis/draft.txt thesis/quotes.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-70", "source": "

The first argument tells mv what we’re ‘moving’,\nwhile the second is where it’s to go.\nIn this case,\nwe’re moving thesis/draft.txt to thesis/quotes.txt,\nwhich has the same effect as renaming the file.\nSure enough,\nls shows us that thesis now contains one file called quotes.txt:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-71", "source": [ "ls thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-72", "source": "

One must be careful when specifying the target file name, since mv will\nsilently overwrite any existing file with the same name, which could\nlead to data loss. An additional option, mv -i (or mv --interactive),\ncan be used to make mv ask you for confirmation before overwriting.

\n

Note that mv also works on directories.

\n

Let’s move quotes.txt into the current working directory.\nWe use mv once again,\nbut this time we’ll use just the name of a directory as the second argument\nto tell mv that we want to keep the filename\nbut put the file somewhere new.\n(This is why the command is called ‘move’.)\nIn this case,\nthe directory name we use is the special directory name . that we mentioned earlier.

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-73", "source": [ "mv thesis/quotes.txt ." ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-74", "source": "

The effect is to move the file from the directory it was in to the current working directory.\nls now shows us that thesis is empty:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-75", "source": [ "ls thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-76", "source": "

Alternatively, we can confirm the file quotes.txt is no longer present in the thesis directory\nby explicitly trying to list it:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-77", "source": [ "ls thesis/quotes.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-78", "source": "

ls with a filename or directory as an argument only lists the requested file or directory.\nIf the file given as the argument doesn’t exist, the shell returns an error as we saw above.\nWe can use this to see that quotes.txt is now present in our current directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-79", "source": [ "ls quotes.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-80", "source": "
\n

❓ Moving Files to a new folder

\n

After running the following commands,\nJamie realizes that she put the files sucrose.dat and maltose.dat into the wrong folder.\nThe files should have been placed in the raw folder.

\n
$ ls -F\n analyzed/ raw/\n$ ls -F analyzed\nfructose.dat glucose.dat maltose.dat sucrose.dat\n$ cd analyzed\n
\n

Fill in the blanks to move these files to the raw/ folder\n(i.e. the one she forgot to put them in)

\n
mv sucrose.dat maltose.dat ____/____\n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
$ mv sucrose.dat maltose.dat ../raw\n
\n

Recall that .. refers to the parent directory (i.e. one above the current directory)\nand that . refers to the current directory.

\n
\n
\n

Copying files and directories

\n

The cp command works very much like mv,\nexcept it copies a file instead of moving it.\nWe can check that it did the right thing using ls\nwith two paths as arguments — like most Unix commands,\nls can be given multiple paths at once:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-81", "source": [ "cp quotes.txt thesis/quotations.txt\n", "ls quotes.txt thesis/quotations.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-82", "source": "

We can also copy a directory and all its contents by using the\nrecursive option -r,\ne.g. to back up a directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-83", "source": [ "cp -r thesis thesis_backup" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-84", "source": "

We can check the result by listing the contents of both the thesis and thesis_backup directory:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-85", "source": [ "ls thesis thesis_backup" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-86", "source": "
\n

❓ Renaming Files

\n

Suppose that you created a plain-text file in your current directory to contain a list of the\nstatistical tests you will need to do to analyze your data, and named it: statstics.txt

\n

After creating and saving this file you realize you misspelled the filename! You want to\ncorrect the mistake, which of the following commands could you use to do so?

\n
    \n
  1. cp statstics.txt statistics.txt
  2. \n
  3. mv statstics.txt statistics.txt
  4. \n
  5. mv statstics.txt .
  6. \n
  7. cp statstics.txt .
  8. \n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
    \n
  1. No. While this would create a file with the correct name,\nthe incorrectly named file still exists in the directory\nand would need to be deleted.
  2. \n
  3. Yes, this would work to rename the file.
  4. \n
  5. No, the period(.) indicates where to move the file, but does not provide a new file name;\nidentical file names\ncannot be created.
  6. \n
  7. No, the period(.) indicates where to copy the file, but does not provide a new file name;\nidentical file names cannot be created.
  8. \n
\n
\n
\n
\n

❓ Moving and Copying

\n

What is the output of the closing ls command in the sequence shown below?

\n
\n

⌨️ Input: Bash

\n
pwd\n
\n
\n
\n

🖥 Output

\n
/Users/jamie/data\n
\n
\n
\n

⌨️ Input: Bash

\n
ls\n
\n
\n
\n

🖥 Output

\n
proteins.dat\n
\n
\n
\n

⌨️ Input: Bash

\n
mkdir recombined\nmv proteins.dat recombined/\ncp recombined/proteins.dat ../proteins-saved.dat\nls\n
\n
\n
    \n
  1. proteins-saved.dat recombined
  2. \n
  3. recombined
  4. \n
  5. proteins.dat recombined
  6. \n
  7. proteins-saved.dat
  8. \n
\n
\n

👁 Solution

\n

We start in the /Users/jamie/data directory, and create a new folder called recombined.\nThe second line moves (mv) the file proteins.dat to the new folder (recombined).\nThe third line makes a copy of the file we just moved.\nThe tricky part here is where the file was copied to.\nRecall that .. means ‘go up a level’, so the copied file is now in /Users/jamie.\nNotice that .. is interpreted with respect to the current working\ndirectory, not with respect to the location of the file being copied.\nSo, the only thing that will show using ls (in /Users/jamie/data) is the recombined folder.

\n
    \n
  1. No, see explanation above. proteins-saved.dat is located at /Users/jamie
  2. \n
  3. Yes
  4. \n
  5. No, see explanation above. proteins.dat is located at /Users/jamie/data/recombined
  6. \n
  7. No, see explanation above. proteins-saved.dat is located at /Users/jamie
  8. \n
\n
\n
\n

Removing files and directories

\n

Returning to the shell-lesson-data directory,\nlet’s tidy up this directory by removing the quotes.txt file we created.\nThe Unix command we’ll use for this is rm (short for ‘remove’):

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-87", "source": [ "rm quotes.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-88", "source": "

We can confirm the file has gone using ls:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-89", "source": [ "ls quotes.txt" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-90", "source": "
\n

Deleting Is Forever

\n

The Unix shell doesn’t have a trash bin that we can recover deleted\nfiles from (though most graphical interfaces to Unix do). Instead,\nwhen we delete files, they are unlinked from the file system so that\ntheir storage space on disk can be recycled. Tools for finding and\nrecovering deleted files do exist, but there’s no guarantee they’ll\nwork in any particular situation, since the computer may recycle the\nfile’s disk space right away.

\n
\n
\n

❓ Using rm Safely

\n

What happens when we execute rm -i thesis_backup/quotations.txt?\nWhy would we want this protection when using rm?

\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
$ rm: remove regular file 'thesis_backup/quotations.txt'? y\n
\n

The -i option will prompt before (every) removal (use Y to confirm deletion\nor N to keep the file).\nThe Unix shell doesn’t have a trash bin, so all the files removed will disappear forever.\nBy using the -i option, we have the chance to check that we are deleting only the files\nthat we want to remove.

\n
\n
\n

If we try to remove the thesis directory using rm thesis,\nwe get an error message:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-91", "source": [ "rm thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-92", "source": "

This happens because rm by default only works on files, not directories.

\n

rm can remove a directory and all its contents if we use the\nrecursive option -r, and it will do so without any confirmation prompts:

\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-93", "source": [ "rm -r thesis" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-94", "source": "

Given that there is no way to retrieve files deleted using the shell,\nrm -r should be used with great caution\n(you might consider adding the interactive option rm -r -i).

\n

Operations with multiple files and directories

\n

Oftentimes one needs to copy or move several files at once.\nThis can be done by providing a list of individual filenames,\nor specifying a naming pattern using wildcards.

\n
\n

❓ Copy with Multiple Filenames

\n

For this exercise, you can test the commands in the shell-lesson-data/data directory.

\n

In the example below, what does cp do when given several filenames and a directory name?

\n
\n

⌨️ Input: Bash

\n
$ mkdir backup\n$ cp amino-acids.txt animals.txt backup/\n
\n
\n

In the example below, what does cp do when given three or more file names?

\n
\n

⌨️ Input: Bash

\n
$ ls -F\namino-acids.txt  animals.txt  backup/  elements/  morse.txt  pdb/\nplanets.txt  salmon.txt  sunspot.txt\n$ cp amino-acids.txt animals.txt morse.txt\n
\n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n

If given more than one file name followed by a directory name\n(i.e. the destination directory must be the last argument),\ncp copies the files to the named directory.

\n

If given three file names, cp throws an error such as the one below,\nbecause it is expecting a directory name as the last argument.

\n
cp: target 'morse.txt' is not a directory\n
\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-95", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-96", "source": "

Using wildcards for accessing multiple files at once

\n
\n

💡 Wildcards

\n

* is a wildcard, which matches zero or more characters.\nLet’s consider the shell-lesson-data/molecules directory:\n*.pdb matches ethane.pdb, propane.pdb, and every\nfile that ends with ‘.pdb’. On the other hand, p*.pdb only matches\npentane.pdb and propane.pdb, because the ‘p’ at the front only\nmatches filenames that begin with the letter ‘p’.

\n

? is also a wildcard, but it matches exactly one character.\nSo ?ethane.pdb would match methane.pdb whereas\n*ethane.pdb matches both ethane.pdb, and methane.pdb.

\n

Wildcards can be used in combination with each other\ne.g. ???ane.pdb matches three characters followed by ane.pdb,\ngiving cubane.pdb ethane.pdb octane.pdb.

\n

When the shell sees a wildcard, it expands the wildcard to create a\nlist of matching filenames before running the command that was\nasked for. As an exception, if a wildcard expression does not match\nany file, Bash will pass the expression as an argument to the command\nas it is. For example, typing ls *.pdf in the molecules directory\n(which contains only files with names ending with .pdb) results in\nan error message that there is no file called *.pdf.\nHowever, generally commands like wc and ls see the lists of\nfile names matching these expressions, but not the wildcards\nthemselves. It is the shell, not the other programs, that deals with\nexpanding wildcards.

\n
\n
\n

❓ List filenames matching a pattern

\n

When run in the molecules directory, which ls command(s) will\nproduce this output?

\n

ethane.pdb methane.pdb

\n
    \n
  1. ls *t*ane.pdb
  2. \n
  3. ls *t?ne.*
  4. \n
  5. ls *t??ne.pdb
  6. \n
  7. ls ethane.*
  8. \n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n

The solution is 3.

\n

1. shows all files whose names contain zero or more characters (*)\nfollowed by the letter t,\nthen zero or more characters (*) followed by ane.pdb.\nThis gives ethane.pdb methane.pdb octane.pdb pentane.pdb.

\n

2. shows all files whose names start with zero or more characters (*) followed by\nthe letter t,\nthen a single character (?), then ne. followed by zero or more characters (*).\nThis will give us octane.pdb and pentane.pdb but doesn’t match anything\nwhich ends in thane.pdb.

\n

3. fixes the problems of option 2 by matching two characters (??) between t and ne.\nThis is the solution.

\n

4. only shows files starting with ethane..

\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-97", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-98", "source": "
\n

❓ More on Wildcards

\n

Sam has a directory containing calibration data, datasets, and descriptions of\nthe datasets:

\n
.\n├── 2015-10-23-calibration.txt\n├── 2015-10-23-dataset1.txt\n├── 2015-10-23-dataset2.txt\n├── 2015-10-23-dataset_overview.txt\n├── 2015-10-26-calibration.txt\n├── 2015-10-26-dataset1.txt\n├── 2015-10-26-dataset2.txt\n├── 2015-10-26-dataset_overview.txt\n├── 2015-11-23-calibration.txt\n├── 2015-11-23-dataset1.txt\n├── 2015-11-23-dataset2.txt\n├── 2015-11-23-dataset_overview.txt\n├── backup\n│   ├── calibration\n│   └── datasets\n└── send_to_bob\n    ├── all_datasets_created_on_a_23rd\n    └── all_november_files\n
\n

Before heading off to another field trip, she wants to back up her data and\nsend some datasets to her colleague Bob. Sam uses the following commands\nto get the job done:

\n
$ cp *dataset* backup/datasets\n$ cp ____calibration____ backup/calibration\n$ cp 2015-____-____ send_to_bob/all_november_files/\n$ cp ____ send_to_bob/all_datasets_created_on_a_23rd/\n
\n

Help Sam by filling in the blanks.

\n

The resulting directory structure should look like this

\n
.\n├── 2015-10-23-calibration.txt\n├── 2015-10-23-dataset1.txt\n├── 2015-10-23-dataset2.txt\n├── 2015-10-23-dataset_overview.txt\n├── 2015-10-26-calibration.txt\n├── 2015-10-26-dataset1.txt\n├── 2015-10-26-dataset2.txt\n├── 2015-10-26-dataset_overview.txt\n├── 2015-11-23-calibration.txt\n├── 2015-11-23-dataset1.txt\n├── 2015-11-23-dataset2.txt\n├── 2015-11-23-dataset_overview.txt\n├── backup\n│   ├── calibration\n│   │   ├── 2015-10-23-calibration.txt\n│   │   ├── 2015-10-26-calibration.txt\n│   │   └── 2015-11-23-calibration.txt\n│   └── datasets\n│       ├── 2015-10-23-dataset1.txt\n│       ├── 2015-10-23-dataset2.txt\n│       ├── 2015-10-23-dataset_overview.txt\n│       ├── 2015-10-26-dataset1.txt\n│       ├── 2015-10-26-dataset2.txt\n│       ├── 2015-10-26-dataset_overview.txt\n│       ├── 2015-11-23-dataset1.txt\n│       ├── 2015-11-23-dataset2.txt\n│       └── 2015-11-23-dataset_overview.txt\n└── send_to_bob\n    ├── all_datasets_created_on_a_23rd\n    │   ├── 2015-10-23-dataset1.txt\n    │   ├── 2015-10-23-dataset2.txt\n    │   ├── 2015-10-23-dataset_overview.txt\n    │   ├── 2015-11-23-dataset1.txt\n    │   ├── 2015-11-23-dataset2.txt\n    │   └── 2015-11-23-dataset_overview.txt\n    └── all_november_files\n        ├── 2015-11-23-calibration.txt\n        ├── 2015-11-23-dataset1.txt\n        ├── 2015-11-23-dataset2.txt\n        └── 2015-11-23-dataset_overview.txt\n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
cp *calibration.txt backup/calibration\ncp 2015-11-* send_to_bob/all_november_files/\ncp *-23-dataset* send_to_bob/all_datasets_created_on_a_23rd/\n
\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-99", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-100", "source": "
\n

❓ Organizing Directories and Files

\n

Jamie is working on a project and she sees that her files aren’t very well\norganized:

\n
$ ls -F\nanalyzed/  fructose.dat    raw/   sucrose.dat\n
\n

The fructose.dat and sucrose.dat files contain output from her data\nanalysis. What command(s) covered in this lesson does she need to run\nso that the commands below will produce the output shown?

\n
$ ls -F\nanalyzed/   raw/\n$ ls analyzed\nfructose.dat    sucrose.dat\n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n
mv *.dat analyzed\n
\n

Jamie needs to move her files fructose.dat and sucrose.dat to the analyzed directory.\nThe shell will expand *.dat to match all .dat files in the current directory.\nThe mv command then moves the list of .dat files to the ‘analyzed’ directory.

\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-101", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-102", "source": "
\n

❓ Reproduce a folder structure

\n

You’re starting a new experiment and would like to duplicate the directory\nstructure from your previous experiment so you can add new data.

\n

Assume that the previous experiment is in a folder called ‘2016-05-18’,\nwhich contains a data folder that in turn contains folders named raw and\nprocessed that contain data files. The goal is to copy the folder structure\nof the 2016-05-18-data folder into a folder called 2016-05-20\nso that your final directory structure looks like this:

\n
2016-05-20/\n└── data\n   ├── processed\n   └── raw\n
\n

Which of the following set of commands would achieve this objective?\nWhat would the other commands do?

\n
\n

⌨️ Option 1

\n
$ mkdir 2016-05-20\n$ mkdir 2016-05-20/data\n$ mkdir 2016-05-20/data/processed\n$ mkdir 2016-05-20/data/raw\n
\n
\n
\n

⌨️ Option 2

\n
$ mkdir 2016-05-20\n$ cd 2016-05-20/\n$ mkdir data/\n$ cd data\n$ mkdir raw processed\n
\n
\n
\n

⌨️ Option 3

\n
$ mkdir 2016-05-20/data/raw\n$ mkdir 2016-05-20/data/processed\n
\n
\n
\n

⌨️ Option 4

\n
$ mkdir -p 2016-05-20/data/raw\n$ mkdir -p 2016-05-20/data/processed\n
\n
\n
\n

⌨️ Option 5

\n
$ mkdir 2016-05-20\n$ cd 2016-05-20\n$ mkdir data\n$ mkdir raw processed\n
\n
\n
\n
Hint: Select the text with your mouse to see the answer

👁 Solution

\n

The first two sets of commands achieve this objective.\nThe first set uses relative paths to create the top-level directory before\nthe subdirectories.

\n

The third set of commands will give an error because the default behavior of mkdir\nwon’t create a subdirectory of a non-existent directory:\nthe intermediate level folders must be created first.

\n

The fourth set of commands achieve this objective. Remember, the -p option,\nfollowed by a path of one or more\ndirectories, will cause mkdir to create any intermediate subdirectories as required.

\n

The final set of commands generates the ‘raw’ and ‘processed’ directories at the same level\nas the ‘data’ directory.

\n
\n
\n", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "id": "cell-103", "source": [ "# Explore the possible solutions here!" ], "cell_type": "code", "execution_count": null, "outputs": [ ], "metadata": { "attributes": { "classes": [ "bash" ], "id": "" } } }, { "id": "cell-104", "source": "", "cell_type": "markdown", "metadata": { "editable": false, "collapsed": false } }, { "cell_type": "markdown", "id": "final-ending-cell", "metadata": { "editable": false, "collapsed": false }, "source": [ "# Key Points\n\n", "- A shell is a program whose primary purpose is to read commands and run other programs.\n", "- This lesson uses Bash, the default shell in many implementations of Unix.\n", "- Programs can be run in Bash by entering commands at the command-line prompt.\n", "- The shell's main advantages are its high action-to-keystroke ratio, its support for automating repetitive tasks, and its capacity to access networked machines.\n", "- The shell's main disadvantages are its primarily textual nature and how cryptic its commands and operation can be.\n", "- The file system is responsible for managing information on the disk.\n", "- Information is stored in files, which are stored in directories (folders).\n", "- Directories can also store other directories, which then form a directory tree.\n", "- `cd [path]` changes the current working directory.\n", "- `ls [path]` prints a listing of a specific file or directory; `ls` on its own lists the current working directory.\n", "- `pwd` prints the user's current working directory.\n", "- `/` on its own is the root directory of the whole file system.\n", "- Most commands take options (flags) that begin with a `-`.\n", "- A relative path specifies a location starting from the current location.\n", "- An absolute path specifies a location from the root of the file system.\n", "- Directory names in a path are separated with `/` on Unix, but `\\` on Windows.\n", "- `..` means 'the directory above the current one'; `.` on its own means 'the current directory'.\n", "- `cp [old] [new]` copies a file.\n", "- `mkdir [path]` creates a new directory.\n", "- `mv [old] [new]` moves (renames) a file or directory.\n", "- `rm [path]` removes (deletes) a file.\n", "- `*` matches zero or more characters in a filename, so `*.txt` matches all files ending in `.txt`.\n", "- `?` matches any single character in a filename, so `?.txt` matches `a.txt` but not `any.txt`.\n", "- Use of the Control key may be described in many ways, including `Ctrl-X`, `Control-X`, and `^X`.\n", "- The shell does not have a trash bin: once something is deleted, it's really gone.\n", "- Most files' names are `something.extension`. The extension isn't required, and doesn't guarantee anything, but is normally used to indicate the type of data in the file.\n", "- Depending on the type of work you do, you may need a more powerful text editor than Nano.\n", "\n# Congratulations on successfully completing this tutorial!\n\n", "Please [fill out the feedback on the GTN website](https://training.galaxyproject.org/training-material/topics/data-science/tutorials/cli-basics/tutorial.html#feedback) and check there for further resources!\n" ] } ] }