{ "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": "
This tutorial will walk you through the basics of how to use the Unix command line.
\n\n\n💬 Comment
\nThis 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\nAgenda
\nIn this tutorial, we will cover:
\n\n
\n- Background
\n\n
\n- Setup
\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.
\nWhile 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.
\nBefore 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 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.
\nUsing 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.
\nThe 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.
\nIn 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.
\nLet’s get started.
\nWhen the shell is first opened, you are presented with a prompt,\nindicating that the shell is waiting for input.
\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!
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.
\nThe 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.
\nSo let’s try our first command, ls
which is short for listing.
\n\n✏️ Open a Jupyter Terminal
\nThis 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.
\nHere are some instructions for how to do this on various environments.
\nJupyter on UseGalaxy.* and MyBinder.org
\n\n
\n- \n
\nUse the File → New → Terminal menu to launch a terminal.
\n\n
- \n
\nDisable “Simple” mode in the bottom left hand corner, if it activated.
\n\n
- \n
\nDrag one of the terminal or notebook tabs to the side to have the training materials and terminal side-by-side
\n\n
CoCalc
\n\n
\n- \n
\nUse the Split View functionality of cocalc to split your view into two portions.
\n\n
- \n
\nChange the view of one panel to a terminal
\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\n💡 Command not found
\nIf the shell can’t find a program whose name is the command you typed, it\nwill print an error message such as:
\n\n\n⌨️ Input: Bash
\n\n$ ks\n
\n\n🖥 Output
\n\nks: command not found\n
This might happen if the command was mis-typed or if the program corresponding to that command\nis not installed.
\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.
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.
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.
As a bonus,\nonce she has put a processing pipeline together,\nshe will be able to use it again whenever she collects more data.
\nIn order to achieve her task, Nelle needs to know how to:
\nThe 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.
\nSeveral 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.
\nFirst, 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:
Try running it now.
\n\n\n💡 Home Directory Variation
\nThe home directory path will look different on different operating systems.
\n\n\n
\n\n \n\n\nLinux \nOSX \nJupyter (UseGalaxy/Binder) \nCoCalc \n\n \n\n\n /home/nelle
\n /Users/nelle
\n /home/joyvan
\n /projects/
</code> On Windows, it will be similar to
\nC:\\Documents and Settings\\nelle
orC:\\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.We will also assume that your
\npwd
command returns your user’s home directory.\nIfpwd
returns something different, you may need to navigate there usingcd
\nor some commands in this lesson will not work as written.\nSee Exploring Other Directories for more details\non thecd
command.
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.
\nOn Nelle’s computer, the filesystem looks like this:
\nAt 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
.
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.
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\nSlashes
\nNotice that there are two meanings for the
\n/
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.
Underneath /Users
,\nwe find one directory for each user with an account on Nelle’s machine,\nher colleagues imhotep and larry.
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.
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
:
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:
/
indicates that this is a directory@
indicates a link*
indicates an executableDepending 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\n💡 Real Terminal Tip: Clearing your terminal
\nIf your screen gets too cluttered, you can clear your terminal using the\n
\nclear
command. You can still access previous commands using ↑\nand ↓ to move line-by-line, or by scrolling in your terminal.
ls
has lots of other options. There are two common ways to find out how\nto use a command and what options it accepts:
--help
option to the command,man
--help
optionMany 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\n💡 Unsupported command-line options
\nIf you try to use an option (flag) that is not supported,
\nls
and other commands\nwill usually print an error message similar to:\n\n⌨️ Input: Bash
\n\nls -j\n
\n\n🖥 Output
\n\nls: invalid option -- 'j'\nTry 'ls --help' for more information.\n
man
commandThe other way to learn about ls
is to type
\n\n⌨️ Input: Bash
\n\n$ man ls\n
\n\n🖥 Output
\n\nLS(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
This command will turn your terminal into a page with a description\nof the ls
command and its options.
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).
To quit the man
pages, press Q.
\n\n💡 Manual pages on the web
\nOf 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
\nunix man page
in your search\nquery will help to find relevant results.GNU provides links to its\nmanuals including the\ncore GNU utilities,\nwhich covers many commands introduced within this lesson.
\n
\n\n❓ Exploring More
\nls
FlagsYou can also use two options at the same time. What does the command
\nls
do when used\nwith the-l
option? What about if you use both the-l
and the-h
option?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\nHint: Select the text with your mouse to see the answer👁 Solution
\nThe
\n-l
option makesls
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 like5.3K
\ninstead of5369
.
\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": "❓ Listing in Reverse Chronological Order
\nBy default,
\nls
lists the contents of a directory in alphabetical\norder by name. The commandls -t
lists items by time of last\nchange instead of alphabetically. The commandls -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
\nThe most recently changed file is listed last when using
\n-rt
. This\ncan be very useful for finding your most recent edits or checking to\nsee if a new output file was written.
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:
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.
\nNow that we know the shell-lesson-data
directory is located in current working directory, we\ncan do two things.
First, we can look at its contents, using the same strategy as before, passing\na directory name to ls
:
Second, we can actually change our location to a different directory, so\nwe are no longer located in\nour home directory.
\nThe 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.
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:
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:
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?
\nWith 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.
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
:
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
:
-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.
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
\nIn addition to the hidden directories
\n..
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 standardls
command\nis used.
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?
How can you check what happened? pwd
gives us the answer!
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.
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:
Check that we’ve moved to the right place by running pwd
and ls -F
.
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.
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.
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.
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\n$ pwd\n
\n\n🖥 Output
\n\n/Users/nelle/\n
Then we could run something like:
\n$ cd /Users/nelle/shell-lesson-data\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/
)
pwd\nls -F\n
\n\n💡 Two More Shortcuts
\nThe shell interprets a tilde (
\n~
) 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 nothere/there/Users/nelle/elsewhere
.Another shortcut is the
\n-
(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 executecd -
twice,\nyou end up back in the starting directory.The difference between
\ncd ..
andcd -
is\nthat the former brings you up, while the latter brings you back.
\nTry it out below!
\n
First navigate to ~/Desktop/shell-lesson-data
(you should already be there).
Then cd
into the creatures
directory
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
\nStarting from
\n/Users/amanda/data
,\nwhich of the following commands could Amanda use to navigate to her home directory,\nwhich is/Users/amanda
?\n
\n- \n
cd .
- \n
cd /
- \n
cd /home/amanda
- \n
cd ../..
- \n
cd ~
- \n
cd home
- \n
cd ~/data/..
- \n
cd
- \n
cd ..
\n\n❓ Solution
\n\n
\n- No:
\n.
stands for the current directory.- No:
\n/
stands for the root directory.- No: Amanda’s home directory is
\n/Users/amanda
.- No: this command goes up two levels, i.e. ends in
\n/Users
.- Yes:
\n~
stands for the user’s home directory, in this case/Users/amanda
.- No: this command would navigate into a directory
\nhome
in the current directory, if it exists.- Yes: unnecessarily complicated, but correct.
\n- Yes: shortcut to go back to the user’s home directory.
\n- Yes: goes up one level.
\n
\n\n❓ Relative Path Resolution
\nUsing the filesystem diagram below, if
\npwd
displays/Users/thing
,\nwhat willls -F ../backup
display?\n
\n- \n
../backup: No such file or directory
- \n
2012-12-01 2013-01-08 2013-01-27
- \n
2012-12-01/ 2013-01-08/ 2013-01-27/
- \n
original/ pnas_final/ pnas_sub/
\n
\n\nHint: Select the text with your mouse to see the answer👁 Solution
\n\n
\n- No: there is a directory
\nbackup
in/Users
.- No: this is the content of
\nUsers/thing/backup
, but with..
, we asked for one level further up.- No: see previous explanation.
\n- Yes:
\n../backup/
refers to/Users/backup/
.
\n\n❓
\nls
Reading ComprehensionUsing the filesystem diagram below,\nif
\npwd
displays/Users/backup
,\nand-r
tellsls
to display things in reverse order,\nwhat command(s) will result in the following output:\npnas_sub/ pnas_final/ original/\n
\n
\n
\n- \n
ls pwd
- \n
ls -r -F
- \n
ls -r -F /Users/backup
\n\n👁 Solution
\n\n
\n- No:
\npwd
is not the name of a directory.- Yes:
\nls
without directory argument lists files and directories in the current directory.- Yes: uses the absolute path explicitly.
\n
We have now encountered commands, options, and arguments,\nbut it is perhaps useful to formalise some terminology.
\nConsider 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
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.
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:
$ 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
Putting all that together, our command above gives us a listing\nof files and directories in our shell-lesson-data folder.
\nKnowing 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
\nNelle 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
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.
Now in her current directory shell-lesson-data
,\nNelle can see what files she has using the command:
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
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.
We now know how to explore files and directories,\nbut how do we create them in the first place?
\nLet’s go back to our shell-lesson-data
directory on the Desktop\nand use ls -F
to see what it contains:
You should see folders like the following, if not, you’re in the wrong place!
\ncreatures/ data/ molecules/ north-pacific-gyre/ notes.txt pizza.cfg solar.pdf writing/\n
Let’s create a new directory called thesis
using the command mkdir thesis
\n(which has no output):
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:
Since we’ve just created the thesis
directory, there’s nothing in it yet:
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:
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:
It should look like:
\nproject/:\ndata/ results/\n\nproject/data:\n\nproject/results:\n
\n\n💡 Two ways of doing the same thing
\nUsing 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
\nthesis
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💡 Good names for files and directories
\nComplicated 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
\n- \n
\nDon’t use spaces.
\nSpaces 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
\n-
or_
instead (e.g.north-pacific-gyre/
rather thannorth pacific gyre/
).\nTo test this out, try typingmkdir north pacific gyre
and see what directory (or directories!)\nare made when you check withls -F
.- \n
\nDon’t begin the name with
\n-
(dash).Commands treat names starting with
\n-
as options.- \n
\nStick with letters, numbers,
\n.
(period or ‘full stop’),-
(dash) and_
(underscore).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.
\nIf 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\"\"
).
Let’s change our working directory to thesis
using cd
,\nthen run a text editor called Nano to create a file called draft.txt
:
$ cd thesis\n$ nano draft.txt\n
\n\n⚠️ Nano won’t work in a Jupyter Notebook!
\nNano is an interactive, full screen editor. You’ll need to switch to a proper\nconsole to do this step, if you haven’t already.
\nIn JupyterLab you can find this under the top menu by clicking File -> New -> Terminal
\n
\n\n💡 Which Editor?
\nWhen we say, “
\nnano
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 callednotepad
that can be run from the command line in the same\nway asnano
for the purposes of this lesson.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
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
).
Once our file is saved, we can use Ctrl+X to quit the editor and\nreturn to the shell.
\n\n\n💡 Control, Ctrl, or ^ Key
\nThe 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
\n- \n
Control-X
- \n
Control+X
- \n
Ctrl-X
- \n
Ctrl+X
- \n
^X
- \n
C-x
In nano, along the bottom of the screen you’ll see
\n^G Get Help ^O WriteOut
.\nThis means that you can useControl-G
to get help andControl-O
to save your\nfile.
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\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": "❓ Creating Files a Different Way
\nWe have seen how to create text files using the
\nnano
editor.\nNow, try the following command:\ntouch my_file.txt\n
\n
\n- \n
\nWhat did the
\ntouch
command do?\nWhen you look at your current directory using the GUI file explorer,\ndoes the file show up?- \n
\nUse
\nls -l
to inspect the files. How large ismy_file.txt
?- \n
\nWhen might you want to create a file this way?
\n\n\nHint: Select the text with your mouse to see the answer👁 Solution
\n\n
\n- \n
\nThe
\ntouch
command generates a new file calledmy_file.txt
in\nyour current directory. You\ncan observe this newly generated file by typingls
at the\ncommand line prompt.my_file.txt
can also be viewed in your\nGUI file explorer.- \n
\nWhen you inspect the file with
\nls -l
, note that the size of\nmy_file.txt
is 0 bytes. In other words, it contains no data.\nIf you openmy_file.txt
using your text editor it is blank.- \n
\nSome 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
\n\n💡 What’s In A Name?
\nYou 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
\n.txt
. This is just a convention: we can call a filemythesis
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,.cfg
is a configuration file full of parameters\nfor some program or other,.png
is a PNG image, and so on.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.
\nNaming a PNG image of a whale as
\nwhale.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.
Returning to the shell-lesson-data
directory,
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’:
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
:
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.
Note that mv
also works on directories.
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.
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:
Alternatively, we can confirm the file quotes.txt
is no longer present in the thesis
directory\nby explicitly trying to list it:
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\n❓ Moving Files to a new folder
\nAfter running the following commands,\nJamie realizes that she put the files
\nsucrose.dat
andmaltose.dat
into the wrong folder.\nThe files should have been placed in theraw
folder.\n$ ls -F\n analyzed/ raw/\n$ ls -F analyzed\nfructose.dat glucose.dat maltose.dat sucrose.dat\n$ cd analyzed\n
Fill in the blanks to move these files to the
\nraw/
folder\n(i.e. the one she forgot to put them in)\nmv sucrose.dat maltose.dat ____/____\n
\n\nHint: Select the text with your mouse to see the answer👁 Solution
\n\n$ mv sucrose.dat maltose.dat ../raw\n
Recall that
\n..
refers to the parent directory (i.e. one above the current directory)\nand that.
refers to the current directory.
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:
We can also copy a directory and all its contents by using the\nrecursive option -r
,\ne.g. to back up a directory:
We can check the result by listing the contents of both the thesis
and thesis_backup
directory:
\n\n❓ Renaming Files
\nSuppose 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:
\nstatstics.txt
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
\n- \n
cp statstics.txt statistics.txt
- \n
mv statstics.txt statistics.txt
- \n
mv statstics.txt .
- \n
cp statstics.txt .
\n\nHint: Select the text with your mouse to see the answer👁 Solution
\n\n
\n- 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.
\n- Yes, this would work to rename the file.
\n- No, the period(.) indicates where to move the file, but does not provide a new file name;\nidentical file names\ncannot be created.
\n- No, the period(.) indicates where to copy the file, but does not provide a new file name;\nidentical file names cannot be created.
\n
\n\n❓ Moving and Copying
\nWhat is the output of the closing
\nls
command in the sequence shown below?\n\n⌨️ Input: Bash
\n\npwd\n
\n\n🖥 Output
\n\n/Users/jamie/data\n
\n\n⌨️ Input: Bash
\n\nls\n
\n\n🖥 Output
\n\nproteins.dat\n
\n\n⌨️ Input: Bash
\n\nmkdir recombined\nmv proteins.dat recombined/\ncp recombined/proteins.dat ../proteins-saved.dat\nls\n
\n
\n- \n
proteins-saved.dat recombined
- \n
recombined
- \n
proteins.dat recombined
- \n
proteins-saved.dat
\n\n👁 Solution
\nWe start in the
\n/Users/jamie/data
directory, and create a new folder calledrecombined
.\nThe second line moves (mv
) the fileproteins.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- No, see explanation above.
\nproteins-saved.dat
is located at/Users/jamie
- Yes
\n- No, see explanation above.
\nproteins.dat
is located at/Users/jamie/data/recombined
- No, see explanation above.
\nproteins-saved.dat
is located at/Users/jamie
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’):
We can confirm the file has gone using ls
:
\n\nDeleting Is Forever
\nThe 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
\nrm
SafelyWhat happens when we execute
\nrm -i thesis_backup/quotations.txt
?\nWhy would we want this protection when usingrm
?\n\nHint: Select the text with your mouse to see the answer👁 Solution
\n\n$ rm: remove regular file 'thesis_backup/quotations.txt'? y\n
The
\n-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.
If we try to remove the thesis
directory using rm thesis
,\nwe get an error message:
This happens because rm
by default only works on files, not directories.
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:
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
).
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\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": "❓ Copy with Multiple Filenames
\nFor this exercise, you can test the commands in the
\nshell-lesson-data/data
directory.In the example below, what does
\ncp
do when given several filenames and a directory name?\n\n⌨️ Input: Bash
\n\n$ mkdir backup\n$ cp amino-acids.txt animals.txt backup/\n
In the example below, what does
\ncp
do when given three or more file names?\n\n⌨️ Input: Bash
\n\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\nHint: Select the text with your mouse to see the answer👁 Solution
\nIf given more than one file name followed by a directory name\n(i.e. the destination directory must be the last argument),\n
\ncp
copies the files to the named directory.If given three file names,
\ncp
throws an error such as the one below,\nbecause it is expecting a directory name as the last argument.\ncp: target 'morse.txt' is not a directory\n
\n\n💡 Wildcards
\n\n
*
is a wildcard, which matches zero or more characters.\nLet’s consider theshell-lesson-data/molecules
directory:\n*.pdb
matchesethane.pdb
,propane.pdb
, and every\nfile that ends with ‘.pdb’. On the other hand,p*.pdb
only matches\npentane.pdb
andpropane.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 matchmethane.pdb
whereas\n*ethane.pdb
matches bothethane.pdb
, andmethane.pdb
.Wildcards can be used in combination with each other\ne.g.
\n???ane.pdb
matches three characters followed byane.pdb
,\ngivingcubane.pdb ethane.pdb octane.pdb
.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
\nls *.pdf
in themolecules
directory\n(which contains only files with names ending with.pdb
) results in\nan error message that there is no file calledwc
andls
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", "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": "❓ List filenames matching a pattern
\nWhen run in the
\nmolecules
directory, whichls
command(s) will\nproduce this output?\n
ethane.pdb methane.pdb
\n
\n- \n
ls *t*ane.pdb
- \n
ls *t?ne.*
- \n
ls *t??ne.pdb
- \n
ls ethane.*
\n\nHint: Select the text with your mouse to see the answer👁 Solution
\nThe solution is
\n3.
\n
1.
shows all files whose names contain zero or more characters (*
)\nfollowed by the lettert
,\nthen zero or more characters (*
) followed byane.pdb
.\nThis givesethane.pdb methane.pdb octane.pdb pentane.pdb
.\n
2.
shows all files whose names start with zero or more characters (*
) followed by\nthe lettert
,\nthen a single character (?
), thenne.
followed by zero or more characters (*
).\nThis will give usoctane.pdb
andpentane.pdb
but doesn’t match anything\nwhich ends inthane.pdb
.\n
3.
fixes the problems of option 2 by matching two characters (??
) betweent
andne
.\nThis is the solution.\n
4.
only shows files starting withethane.
.
\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": "❓ More on Wildcards
\nSam has a directory containing calibration data, datasets, and descriptions of\nthe datasets:
\n\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
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\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
Help Sam by filling in the blanks.
\nThe resulting directory structure should look like this
\n\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\nHint: Select the text with your mouse to see the answer👁 Solution
\n\ncp *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", "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": "❓ Organizing Directories and Files
\nJamie is working on a project and she sees that her files aren’t very well\norganized:
\n\n$ ls -F\nanalyzed/ fructose.dat raw/ sucrose.dat\n
The
\nfructose.dat
andsucrose.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\nHint: Select the text with your mouse to see the answer👁 Solution
\n\nmv *.dat analyzed\n
Jamie needs to move her files
\nfructose.dat
andsucrose.dat
to theanalyzed
directory.\nThe shell will expand *.dat to match all .dat files in the current directory.\nThemv
command then moves the list of .dat files to the ‘analyzed’ directory.
\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" ] } ] }❓ Reproduce a folder structure
\nYou’re starting a new experiment and would like to duplicate the directory\nstructure from your previous experiment so you can add new data.
\nAssume that the previous experiment is in a folder called ‘2016-05-18’,\nwhich contains a
\ndata
folder that in turn contains folders namedraw
and\nprocessed
that contain data files. The goal is to copy the folder structure\nof the2016-05-18-data
folder into a folder called2016-05-20
\nso that your final directory structure looks like this:\n2016-05-20/\n└── data\n ├── processed\n └── raw\n
Which of the following set of commands would achieve this objective?\nWhat would the other commands do?
\n\n\n⌨️ Option 1
\n\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⌨️ Option 2
\n\n$ mkdir 2016-05-20\n$ cd 2016-05-20/\n$ mkdir data/\n$ cd data\n$ mkdir raw processed\n
\n\n⌨️ Option 3
\n\n$ mkdir 2016-05-20/data/raw\n$ mkdir 2016-05-20/data/processed\n
\n\n⌨️ Option 4
\n\n$ mkdir -p 2016-05-20/data/raw\n$ mkdir -p 2016-05-20/data/processed\n
\n\n⌨️ Option 5
\n\n$ mkdir 2016-05-20\n$ cd 2016-05-20\n$ mkdir data\n$ mkdir raw processed\n
\n\nHint: Select the text with your mouse to see the answer👁 Solution
\nThe first two sets of commands achieve this objective.\nThe first set uses relative paths to create the top-level directory before\nthe subdirectories.
\nThe third set of commands will give an error because the default behavior of
\nmkdir
\nwon’t create a subdirectory of a non-existent directory:\nthe intermediate level folders must be created first.The fourth set of commands achieve this objective. Remember, the
\n-p
option,\nfollowed by a path of one or more\ndirectories, will causemkdir
to create any intermediate subdirectories as required.The final set of commands generates the ‘raw’ and ‘processed’ directories at the same level\nas the ‘data’ directory.
\n