Command Line Training
Introduction to the Command Line¶
To make the most out of computing infrastructures like the ScienceCloud, ScienceCluster, as well as the Supercomputer - Alps, you may find it helpful to learn to use the Command Line Interface (CLI) for scientific computing.
All our computing services run on open source, Linux-based operating systems. You may have heard of Ubuntu, a popular Linux distribution that also powers massive supercomputers. All nodes in ScienceCluster run on Ubuntu Linux, and by working with ScienceCloud you will be exposed to the Ubuntu Linux, or Debian, one of its variants. See the Context section below for more info about open source and scientific computing.
These training materials should help you:
- Learn the fundamentals about the command line and how it relates to your research computing workflows.
- Introduce yourself to the structure of the Linux filesystem.
- Acquaint yourself with the basic commands and syntax of a shell programming language (which will transfer to multiple shells and operating systems).
Bash
Although many of these concepts apply across shell languages, the provided training materials use the Bash shell language. Using a different shell on your personal computer may result in slight variations from the examples.
For the best experience consider taking the Command Line training workshop.
Getting Started Independently
If you would like to begin practicing on a command line immediately, consider publicly available sites that offer example CLIs: WebVM (which allows user access to a sandboxed CLI) and container2wasm (which offers full root access to a sandboxed CLI).
How do I work through these materials?¶
How much knowledge of the command line do you already have?
If you have previous knowledge of the command line, consider reviewing the guided assessment of these concepts below. You can also use this assessment as way to validate your learning.
Access to your operating system, as well as to ScienceCloud or ScienceCluster, is possible via the command-line interface (CLI), for which a terminal application is required.
The terminal application you use on your local computer depends on your operating system; here are the default options:
- macOS and Linux: use the Terminal application
- Windows: use PowerShell, or consider WSL or Multipass - both will give you the ability to install an Ubuntu Linux virtual machine.
To work through these materials, either use a terminal application on your local machine, or the WebVM site (which allows user access to a sandboxed CLI). For more details about CLI see the What is the "command line"? section below.
These training materials use the Bash shell language. If your operating system's default shell is different than the Bash shell you may get slightly different outputs than shown in these examples.
Check your default shell
To check your default shell in your operating system you can type the following command in the terminal and press Enter: echo $SHELL. The output will display the path to your default shell, e.g. /bin/bash (Bash shell) or /bin/zsh (Z shell). If your operating system's default shell is different than /bin/bash (Bash shell) consider using the WebVM site instead, or switching to a Bash shell by typing the following command in the terminal on your local machine: chsh -s /bin/bash
Whenever you use the ScienceCloud and the ScienceCluster, you will use ssh to connect.
The system commands used in these materials, e.g. ls and pwd, are available across operating systems, whether you work on ScienceCloud or ScienceCluster or on your local machine. The same commands on different systems might return different outputs but the concepts remain the same. Therefore, for your learning and to acquaint yourself with the basic commands and syntax you can choose any system, including the WebVM.
Warming-up question
Open the WebVM site and type the command ls, followed by ENTER. Also open a terminal application on your local machine and type the same command. Do you see differences? (Yes/No)
Show answer
Answer: Yes
The command ls is one of the system commands largely used to list content of directories in a filesystem. It is available across operating systems, however the results may be different because of the different filesystems. You will learn more about filesystems in the Filesystems section below.
What is the "command line"?¶
The "command line" interface (often abbreviated "CLI") is a system that allows users to interact with a computer using typed commands.
Learning how to use a CLI will not only give you greater skills with computers, it will allow you to customize your research workflows so that you can make optimal use of the most powerful computing infrastructures.
Filesystems¶
What is a "filesystem"?¶
At an abstract level, one could model a computer as a machine that necessarily includes:
- Datasets and a system for storing such data
- Programs and applications that run both the computer system itself in addition to manipulating the available data
All data for a computer (i.e., datasets, user software, operating system software, etc.), is stored within what is called a filesystem. It is the filesystem that dictates how data is structured on any storage device (e.g., a hard-drive, a USB stick, etc.).
There are multiple types of filesystems, and not all filesystems are compatible with all computer operating systems.
Examples of filesystems include:
- vfat: an older filesystem used by MS DOS
- ntfs: the default filesystem for Windows
- ext4: the default filesystem in most GNU/Linux distributions; used for ScienceCloud volumes
- apfs: the macOS filesystem
Structure¶
Although not all filesystems are identical, many of them share a similar hierarchical tree structure.
In a hierarchical tree filesystem everything starts from the root directory, which is represented in Bash and other command line languages as /.
The / Character
The / character alone represents the entire root directory and all its subdirectories. If a command acts or operates on the / symbol, especially recursively, then it will affect the entire filesystem.
Here's a diagram of a sample filesystem:
/
├─ bin/
│ └─ ...
├─ home/
│ ├─ user/
│ │ ├─ Documents/ ← this is an example directory!
│ │ │ └─ example.txt ← this is an example file!
│ │ └─ Pictures/
│ │ └─ photo.png
│ └─ second_user/
│ └─ ...
├─ sbin/
│ └─ ...
├─ var/
│ └─ ...
└─ .../
Within a hierarchical filesystem, a directory is a "branch" on the hierarchical tree. When using a GUI to control a computer's files, directories are commonly represented as folders. Thus, files can be thought of as being located at (or within) a specific directory (just as files can be considered as being within folders on a graphical desktop).
Directories themselves can have directories within or under them, which are called subdirectories.
Some familiar directories/locations you will see in many filesystems are:
/bin/: includes essential command binaries that are needed for all users (e.g.ls,cp,cat)/home/: includes all user home directories for the system/sbin/: includes essential system command binaries/var/: includes system variable files that change during normal operation (e.g. logs, cache)
There are many other directories/locations you'll find across operating systems. It's important to remember: not all locations in the filesystem are safe to freely alter. Changing files in certain locations can lead to operating system failure or corruption.
Dotfiles¶
In order to help keep filesystems as accident-proof as possible, filesystems make use of dotfiles. A dotfile is exactly what the name states: a file (or a directory) that begins with a . character.
Unless you take specific actions to display them (e.g., use the -a flag with the ls command), they will not be displayed by default.
Dot Directories
Directories can also start with . (dot directories). As with dotfiles, they are hidden by default. Otherwise, they act like and can be treated like standard directories.
Paths¶
As noted, a directory is a "branch" within a filesystem where files (or other subdirectories) can be located; i.e., a directory is a location in a filesystem.
To refer to any location (i.e., directory or file) within a filesystem, a path to the location of interest is used. There are two types of paths:
- Absolute paths: include the entire location of a directory or file starting from the root directory; absolute paths always start with
/ - Relative paths: include the location of a directory or file in relation (i.e., relative to) the user's current location in the filesystem (see below)
From the sample filesystem above, an example of an absolute path to a file is:
To reiterate: all absolute paths start with /. The same / character is also used in paths (both absolute and relative) to distinguish between depths or levels of the hierarchical tree.
An example of a relative path is:
In contrast to absolute paths, relative paths never begin with /. They describe the path to a file or directory with reference to your current working directory, which is the current location of your session within the filesystem.
The current working directory in the Documents/example.txt example is (with reference to the sample filesystem diagram) the /home/first_user/ directory.
How do you know your current location? The command prompt tells you, or you can use the pwd command.
Further info:
Paths to files and directories are formatted identically, though some programmers prefer to write directory paths with a trailing
/character.In most cases it is equivalent to include the final
/character. However, some command line tools will interpret a path with a trailing/character differently (e.g., rsync).
Beginning on the CLI¶
Command Prompt¶
When you arrive at a CLI you see what is called the command prompt. It is designed to help communicate who and where you are on a system. It often looks something like this:
The values username and hostname in this example are specifically chosen as these are two of the principal values that comprise the command prompt.
Piece by piece, the example command prompt includes:
- the
usernameis your current authenticated username on the computer - the
hostnameis the name of the computer to which your command line session is connected - the
@character separates theusernamefrom thehostname - the
:separates theusername@hostnamefrom the displayed location within the computer's filesystem - the
~is the special symbol used to denote thehomedirectory for the user; this is often the default location when starting a command line session on a machine- the
~symbol will change to show path locations as you navigate through a filesystem (e.g., withcd) - in other words, this part of the command prompt shows your current location within the filesystem
- the
- the
$denotes the end of the command prompt; your typed commands will come afterwards
Further info: The specifics of your command prompt may vary according to your operating system but in general will contain the same information.
Inputting Commands¶
When inputting commands into a command prompt, what exactly happens with/to/from those commands?
To answer this question, it's necessary to understand that a computer's operating system is the entirety of the software (sometimes called the "software stack") that makes the computer functional.
Within the operating system exists a variety of software types including:
- A "kernel": the software that directly controls hardware processes (e.g., memory management, process scheduling, etc.); one of the most commonly encountered kernels is Linux
- System libraries and utilities: collections of code and programs that allow installed applications to interact with the hardware via the kernel; these include the command line programs mentioned below (e.g.,
ls,cp, etc.) - User programs: the software that the user can customize then utilize for their tasks
The shell is one of these user programs. It's the specific software that interprets your commands then executes them. There are a variety of shells used across operating systems:
- Bash: the default shell for many Linux distributions
- ScienceCloud and ScienceCluster users will use Bash
- Zsh: the default shell for macOS, but can also be used in Linux
- PowerShell: the default shell for Windows
These shells share a common command syntax, meaning the skills involved in using one shell language will translate to other shells (and operating systems).
Syntax¶
Command Structure¶
The basic structure of a shell command is as follows:
<command>is the specific command you're using, e.g.ls,cd[--options]modify the default behaviour of the command, e.g.-a,--all<arguments>are the specific inputs to the<command>you're using, often paths to files or directories- Spaces are used to separate commands, options, and arguments
- Multiple options and/or arguments are often allowed
- One or more arguments may be required and the command will fail if they are missing
Options¶
- Option types
- Short
- Start with a single hyphen
-followed by a single letter, e.g.-a,-l - Can be combined, e.g.
ls -alhis the same asls -a -l -h
- Start with a single hyphen
- Long
- Start with two hyphens
--followed by multiple letters and numbers with potentially single hyphens in-between, e.g.--all,--human-readable - Specified individually
- Start with two hyphens
- Short
- Order generally does not matter,
ls -lhis the same asls -hl - Some options require values, e.g.
ssh -i ~/.ssh/keyfile username@<ip_address>where the-ioption is used to specify the identity file to use for connection - Options without values are called flags
Special Symbols¶
There are a number of special characters in most shell languages (including Bash) that reduce how much you need to type. Here are a selection of them:
/: the symbol for the root directory of the filesystem and the delimiter between directories and subdirectories (i.e., depths of the filesystem tree)~: an abbreviation for the home directory (i.e., shorthand for the path to thehomedirectory for the user).: refers to the current working directory; can be used in the same way as a file path..: refers to the parent of the current working directory; can be used in the same way as a file path|: called the pipe character, it forwards the textual output from one command directly into another command as input; e.g., with thegrepfunction>: called the redirection operator, it "redirects" the textual output of a command to write to a new text file or overwrite the existing text file (or value)- ⚠️ use the
>character carefully as it will overwrite existing files/values by default!
- ⚠️ use the
>>: a variation on the redirection operator that appends textual output of a command to a text file (rather than overwriting);: separates commands so that multiple commands can be written then executed via a single line of text
Fundamentals¶
File Permissions¶
Before operating too many commands on files in a filesystem it's first helpful to understand permissions.
Permissions are the concept in an operating system that allow multi-user functionality in a safe, secure, and accident-reduced way.
Without the appropriate permissions, you (as a user) may or may not be able to:
- read a file/directory
- write to (i.e., change) a file/directory
- execute (i.e., run) a file
File permissions are structured so that multiple users on the same machine can have a unified, accident-protected, and secure way to manage their files.
The easiest way to see file permissions (in your current working directory) is to run ls -l. The output should resemble the following (fabricated example):
drwxrwxrwx 2 user group 4096 Jan 01 00:00 Documents
-rwxr--r-- 1 second_user second_group 4096 Jan 01 00:00 example.txt
The first 10 characters of each line share a common format:
- the first character will be a
dfor directory or-for not a directory - the next 9 characters are separated into 3 sets of 3 characters; each set of characters is identical in format, defining read (
r), write (w), and execute (x) permissions for:user,group, andother- a value of
-means that specific permission is not assigned; a value ofr,w, orxindicates the specific permission is assigned
- the first column of numbers (
2and1) is usually a number indicating the number of values (i.e., files and directories) underneath an entry - the next 2 columns denote the
userandgroupassignment for the file/directory- the assigned
userhas read, write, execute permissions defined via the first series of 3 characters - the assigned
grouphas read, write, execute permissions defined in the second series of 3 characters - users on the machine that are not named
userand are also not a member of an entry's assignedgrouphave permissions defined in the third series of 3 characters (i.e.,other)
- the assigned
This text-based diagram may be helpful:
1 2 3 4 5 6 7 8 9 10
| | | | | | | | | |
- r w x r - - r - -
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | +--- `other` execute (-)
| | | | | | | | +----- `other` write (-)
| | | | | | | +------- `other` read (r)
| | | | | | +--------- `group` execute (-)
| | | | | +----------- `group` write (-)
| | | | +------------- `group` read (r)
| | | +--------------- `user` execute (x)
| | +----------------- `user` write (w)
| +------------------- `user` read (r)
+--------------------- entry type:
d = directory
- = regular file
The principal commands to edit permissions and ownership values are chmod and chown.
The special command sudo can be prepended to any other commands to "elevate" the command so it's treated as having been run by the special root user. The root user is a default user written into the operating system that has complete control over all aspects of a filesystem.
sudo Access
Due to the security issues and accident-potential associated with sudo and root permissions, only specific systems from Science IT allow sudo access. Please plan your workflow accordingly:
- ScienceCloud VMs, launched and managed by a user, come equipped with root access by default (secured by default using SSH keys).
- ScienceCluster and the Alps System do not allow users
sudoandrootpermissions.
File Types¶
When operating on a command line it's helpful to categorize files into 2 types:
- Binary files: require a specific program/application to be used or read; e.g.,
.mp3,.pdf,.doc - Text files: as the name states, they contain purely alphanumeric text and can be edited interactively
To confirm a file's type use the file command.
To open a binary file you execute it using the command corresponding to its required program; for example:
You as a user will need to ensure you select the correct program/application command for the target binary file.Editing Text Files¶
There are several ways to edit text directly from the command line. Some popular full-terminal text editors include:
nano: the default editor on most GNU/Linux systems; beginner-friendly and easy to usepico: similar to nano but more lightweightvi: a powerful and efficient UNIX editor; has a steeper learning curve that may be challenging for beginners
For beginners, it's helpful to know how to start and stop nano:
- To start
nano, simply execute the commandnanoand your terminal application will move to thenanointerface creating a blank document- To edit a specific text file with
nano, runnano <path_to_text_file>
- To edit a specific text file with
- You can freely type with your cursor in this interface as well as paste text copied from your local computer
- When you are finished editing you can exit:
- Press
control + Xto initiate the exit procedure - When asked
Save modified buffer?typeyto confirm that you want to save the changes (ornto cancel without saving) - When prompted for the
File name: ...either update the file name or pressenterto confirm the inputted file name
- Press
Commands¶
While there are innumerable commands on any command line, here are commands (with useful flags as noted) to consider for research and scientific computing:
The -h / --help flag
For many, but not all, commands the -h/--help flag is conventionally used to display the help dialogue for a command.
Metadata¶
man: opens the manual for a command; i.e., it's used on other commands; e.g.,man lsls: lists the content of a directory; common flags:-a,-l,-hlsblk: lists the storage devices on the systemdf: displays usage of the storage devices; common flags:-hps: displays process statistics; common flags:aux,-eftopandhtop: used for monitoring and benchmarking
Viewing Files¶
file: show the file typecat: print the content of a text fileecho: prints a character string of interestecho $USER: prints your username, where $USER is an environment variable storing the name of the currently logged-in userless: open a text file to read it in your terminal; typeqto exittailandhead: print the end/beginning of a file, respectively; common flags:-n <number>grep: stands for "global regular expression parse"- used to find specific character strings within text,
grep <pattern> <filename> - often being fed data via the
|operator:ps aux | grep ssh, to list all processes containing "ssh"
- used to find specific character strings within text,
Filesystem Navigation¶
pwd: prints the current working directorycd: changes the current directory to a directory of your choosingcd -: brings you to the previous directory you were incd ..: moves you one directory level up from your current locationcd ~: will always bring you$HOME
Moving and Copying¶
cp: copy files and directories- usage:
cp [options] <source> <destination> - common flags:
-rfor recursive (i.e., apply to a directory and its contents)
- usage:
mv: moves files from one location to another; also used for renaming- usage:
mv [options] <source> <destination> mvis always recursive!mv -i: prompt before overwrite
- usage:
mkdirandrmdir: make and remove an empty directory, respectivelyrm: remove files and directoriesrm -i: prompt before each removal, giving you a chance to confirm- common flags:
-rfor recursive (i.e., apply to a directory and its contents) - ⚠️ the
rmcommand does not move files to a trash bin or temporary location, it immediately removes them; use with caution
- common flags:
File Transfer¶
See our documentation on scp and rsync.
To make a "clone" of a remote git repository, you can use:
Permissions¶
chmod: change the permissions of files and directories- usage:
chmod [options] <file>- common flags:
[ugo]±r,[ugo]±w,[ugo]±x - e.g.,
chmod u+x,o-w fileaddsexecutepermissions for theuserand removeswritepermissions forother
- common flags:
- alternatively, the graphics below show how to compose the
chmodnumeric (octal) format for changing file permissions- the syntax for the example in the table would be
chmod 754 <file>
- the syntax for the example in the table would be
- usage:
+----------+--------+--------+--------+--------------+----------+
| Class | r (4) | w (2) | x (1) | Total (sum) | Symbolic |
+----------+--------+--------+--------+--------------+----------+
| Owner | 4 | 2 | 1 | 4+2+1 = 7 | rwx |
| Group | 4 | 0 | 1 | 4+0+1 = 5 | r-x |
| Others | 4 | 0 | 0 | 4+0+0 = 4 | r-- |
+----------+--------+--------+--------+--------------+----------+
+-------+----------+------------------+
| Octal | Symbolic | Meaning |
+-------+----------+------------------+
| 0 | --- | none |
| 1 | --x | exec |
| 2 | -w- | write |
| 3 | -wx | write + exec |
| 4 | r-- | read |
| 5 | r-x | read + exec |
| 6 | rw- | read + write |
| 7 | rwx | all |
+-------+----------+------------------+
chown: change ownership of files and directories- usage:
chown <user>:<group> <file>
- usage:
sudo: prepended to a command to execute it as the superuser (i.e., "superuser do")- requires the current user to have
sudo/rootpermissions - requires authentication
- requires the current user to have
Installing Software¶
aptis the default package (i.e., software) manager on Ubuntu- make sure to run
apt update(orsudo apt update) before running anyapt installcommands apt installinstalls software directly onto the local computer in the user's space; this may work well for private/lab computers or ScienceCloud VMs, but consider other methods for software installation- alternative methods to consider are
uv,conda/miniforge/mamba, and most importantly containers
- make sure to run
Connecting to Remote Computers¶
ssh: stands for "secure shell" and is the principal tool used to establish secure connections to remote machines
See our documentation on ssh, ssh key generation, and more.
Context¶
Open Source Operating Systems¶
By working with virtual machines on the command line for scientific research, you by default will be exposed to an entire open-source operating system. Very often it will be a distribution of Linux called Ubuntu, but there are many variants (e.g., Debian, Fedora, Arch).
'Distributions'
A "distribution" of Linux means a version of an operating system based on the Linux kernel. All Linux distributions share the same kernel but differ in other parts of the software stack. At Science IT, the recommended and default version is Ubuntu. It is widely considered one of the most user friendly distributions, especially for beginners.
Open-source operating systems (and communities) like these form the basis of large scale scientific (and non-scientific) computing.
As a researcher via the command line you can, for example, install software to customize your runtime environment then share your software stack setup with other researchers so they can replicate your work on their own computing hardware.
Moreover, by using open-source operating systems and software, researchers support the UZH's commitment to Open Science.
Scripting¶
Here's an example of a for-loop in Bash, which squares the integers between 1 and 10.
After you learn how to run commands one at a time, the next step is to write shell scripts — small files that tell the computer to execute those commands in a sequence.
First, create the file you want to run, in this case, called squares.sh.
To make it complete, put a "shebang line", which is a series of characters that always go on the 1st line of the script and tells the shell which default command (i.e., binary) should be used when running it.
An example shebang line for bash is:
Then add your specific code of interest:
Meaning the full script would be:
Then, run it:
Since you have added a shebang line, the shell already knows that the script should be executed with bash. However, the file needs execute permission to be launched directly, which can be added with
Now, you can run it as:
Shell scripts form the basis for extending your control of a computer so the machine acts according to your instructions without requiring your presence. In other words, they let you automate computers to run workflows for you.
Of particular note, shell scripts (Bash) are how users submit jobs in cluster environments.
Guided Assessment of the Training Concepts¶
The following questions are meant to show how the concepts introduced in this training material work in practice and let you gauge what you still need to review. They are designed to be run in WebVM, so you can practice the commands directly in your browser. Use the hints in the "Show answer" blocks to jump to the relevant sections and review the topics as necessary.
User or Superuser
1) Focus on the command prompt user@:~$ when opening the WebVM site. Can you tell: what is your username on the WebVM terminal session?
Show answer
Answer: Your username on the system is user
You can get information about who you are on the system from the command prompt, which is what you see when you access an operating system via a CLI. The command prompt is designed to communicate specific information; i.e. the name of the computer you are connected to (called the host name) as well as where you are located on the system. For more details check the Command Prompt section.
2) If you connect to ScienceCluster using the command ssh shortname@cluster.s3it.uzh.ch, in which directory are you located on the machine upon login? (Tip: if you are a ScienceCluster user, connect to a login node via the following instructions and inspect the command prompt.)
Show answer
Answer: /home/username or ~
The default location when starting a command line session on a machine is the home directory for the user; i.e., you'll see /home/username or ~ (the special symbol used to abbreviate the home directory). See the Special Symbols section below for more examples.
username is a subdirectory of the home directory in the ScienceCluster filesystem; see the Filesystem structure section for more details. Note: the ScienceCluster is a multiuser system, and the default location upon login for each user of the cluster is a subdirectory of home named as the user's UZH shortname.
3) On the WebVM session, type the ls -l command, and press Enter. You will get the following output:
dr-xr-xr-x 0 root root 0 Jan 1 1970 documents
drwxr-xr-x 7 user user 4096 Jun 1 15:22 examples
Can you tell which subdirectory belongs to the superuser?
Show answer
Answer: The documents subdirectory belongs to the root user, which is by default a superuser with sudo/root permissions.
The root user is a default user written into the operating system that by default has complete control over all aspects of a filesystem. A regular user can be granted sudo/root permissions and execute commands as superuser by prepending the special command sudo to them. See the File Permissions section below for more details.
Note: only specific systems from Science IT allow sudo access; ScienceCloud users have root access by default on all launched VMs; ScienceCluster and the Alps System do not allow users sudo and root permissions. To acquaint yourself with root privileges use the container2wasm site, which offers full root access to a sandboxed CLI.
Exploring data on a filesystem
1) If you run ls -l on the WebVM you will get the following output:
dr-xr-xr-x 0 root root 0 Jan 1 1970 documents
drwxr-xr-x 7 user user 4096 Jun 1 15:22 examples
Can you tell whether documents or examples are files or directories?
Show answer
Answer: They are both directories.
The easiest way to check whether the current working directory contains files or other directories is to run ls -l. The first 10 characters of each line in the output share a common format: the first character will be a d for directory or - otherwise. The next characters tell you about permissions, ownership, and size. If you are interested, you can get more details about the ls command by typing ls --help. The -h/--help flag is conventionally used to display the help dialogue for a command.
The operating system uses directories to track where files are stored, just like using folders to organise files on a graphical desktop. Filesystems have a hierarchical structure that resembles an upside-down tree, with the root directory at the top containing all user directories. The root directory is represented in Bash and other command line languages as /. See the Filesystem structure section below for more details.
2) You can navigate through the filesystem structure by using the command cd. Upon login your current working directory is your home directory (~), as you can tell from the command prompt user@:~$ or by typing pwd. Check how the command prompt changes when typing cd examples. Then type the command cd .. and afterwards cd -; can you tell what those commands do? (Tip: to go back to your home type cd ~.)
Show answer
Answer: cd .. brings you to the parent of the current working directory, while cd - brings you back to your previous location.
Being able to navigate through the directory structure is important to get to your data and files. The cd and the pwd commands can help you get information about the current directory or change to a directory of your choosing without altering the content of the filesystem. See also the Filesystem Navigation section.
The .. and - are special symbols; you can read more about them in the Special Symbols section.
3) What happens if you type the command cd .?
Show answer
Answer: Nothing happens; your location remains the same.
The dot . is another special symbol that refers to the current working directory. It indicates the location of files that are in the directory you are currently working in.
4) Navigate to the examples directory and list the content of the python3 subdirectory using the cd and ls commands. Can you find the pi.py file?
Show answer
Answer: Starting from your home directory type cd examples, cd python3, and then ls.
You can check that you are in the python3 subdirectory by typing the command pwd; it will show the absolute path /home/user/examples/python3. From here, if you run ls -l, you will see that the first character is a -—so "not a directory". Another important difference between files and directories is that often files have an extension; e.g., .pdf, .txt, .py. Files can be categorized into two main file types: binary files requiring a specific program/application to be used or read, and text files containing purely alphanumeric text that can be edited interactively. See the File types section for more examples.
For most of the commands you use (e.g., ls, cd), you can modify the flags to select specific options. Check the Command Structure section for more details.
5) Go back to your home directory with the command cd ~, then run the command cd examples/python3/. Does the output of the ls command still show pi.py among the content?
Show answer
Answer: Yes, it is the same command as before but using a relative path.
If you know the location of your file in the filesystem it is possible to navigate to it using a relative path, which is the path to a file or directory with reference to your current working directory. Note that relative paths never begin with /, in contrast to absolute paths. If you type cd /examples/python3 you get the following error: No such file or directory. We'll see more examples of relative and absolute paths again. For more info you can also check the Paths section.
6) Go back to your home directory with the command cd ~, then run the command cd ./examples/python3/. Can you explain why you come to the same location as before?
Show answer
Answer: The ./ is a relative path indicating the files in the current directory. It can be omitted (that's why cd examples/python3 also works), but using it while indicating a file's location helps avoid ambiguity.
The . symbol refers to the current directory, and the / is here used as delimiter between the current working directory and the examples subdirectory.
Read, write, execute files - explore file permissions
1) The files in the python3 directory belong to you: the ls -l command shows that the owner is user. Can you tell from the ls -l output whether you have read/write/execute permissions on the files?
Show answer
Answer: For all three files in the python3 directory the owner has read and write permissions but not execute.
The first 10 characters of the ls -l output looks like -rw-rw-r--. The first - character means it's a regular file (not a directory); the next 9 characters are separated into 3 sets of 3 characters. Each set of characters is identical in format, defining read (r), write (w), and execute (x) permissions for user, group, and other. Users are individual accounts that can log into the system and own/manage their own files; groups are collections of users that share permissions; and others refer to all users who are not the owner of a file or part of its assigned group. Both user and group have permissions for reading and writing these specific files (rw-), while other users have read-only permission (r--). Note that a value of - means that specific permission is not assigned. See the File Permissions section for more details.
2) Read the content of the pi.py file using a command that can scroll if necessary. (Tip: you'll need to type q to exit)
Show answer
Answer: The command to use is less pi.py
The less command is mostly used to display the contents of a file. You can find other alternative tools in the Viewing Files section. In contrast to text editors, less displays the content one page at a time and doesn't need to read the whole file at startup; as such, it is mostly used for opening large files. Check the output of less --help for more advanced features and how to navigate both forward and backward through the file.
3) Write a "shebang" #!/usr/bin/env python3 line at the beginning of the pi.py file.
Show answer
Answer: The command to use is nano pi.py
You can use the nano command to edit the file, as explained in the Editing Text Files section. (Optional: you can check the modified file using the less command.) The nano application is the default editor on most GNU/Linux systems. Alternative tools are pico and the more advanced vi. In the Editing Text Files section you can find instructions on how to start and stop nano. You can explore additional functionalities by running nano --help.
4) Execute the pi.py script with the command ./pi.py (it will use python3 as specified in the "shebang"). What does the bash: ./pi.py: Permission denied error mean?
Show answer
Answer: Although the files belong to you (the file owner is user), the user has only read and write permissions on the file (rw-rw-r--).
The ./ notation is also commonly used to run scripts or programs that are located in the current directory: the script name pi.py gets prefixed with ./.
Note: without the "shebang" line in the script, the command uses a different interpreter and returns a different error: ./pi.py: line 3: syntax error. You can directly use the Python interpreter by running the command python3 pi.py, which will then run without errors. This is because the python interpreter (python3) is what is actually executed, and the script file doesn't need to be an executable.
5) Change permissions to the pi.py file so you can execute the ./pi.py script as a command without an error.
Show answer
Answer: The command to use is chmod u+x pi.py, or the octal form chmod 762 pi.py
Check chmod --help or the Permissions section for more instructions. Common flags are: [ugo]±r, [ugo]±w, [ugo]±x. The command chmod u+x pi.py adds (+) execute permissions (x) to the user and owner of the file (u). Alternatively you can use the octal format for changing the file permission: each octal digit 7, 6, and 2 represents the value of a 3-digit binary number. Therefore 7 6 2 can be represented as 111 110 100; if you consider a 0 as a "not assigned permission", this translates to rwx rw- r--. You can see the graphics in the Permissions section for how to compose the chmod numeric (octal) format for changing file permissions. You can change permissions only for files you own. To change other users' files you need root/sudo permission, which is possible on ScienceCloud VMs (where you are root by default) but not on the ScienceCluster.
Managing outputs - the pi.py example
1) Run the pi.py script from within the /home/user/examples/python3 directory but let's redirect its output to a file pi.out instead of having it printed directly to the terminal as "standard output".
Show answer
Answer: use the redirection operator >, so the command python3 pi.py > pi.out (or ./pi.py > pi.out, if you changed the permission for pi.py to rwx rw- r--)
When the analysis scripts write their output directly to standard output, reviewing or debugging results can be challenging. The redirection operator > "redirects" the textual output of a command to a new text file. It is one of the widely used special symbols, and you can read more about it in the corresponding section.
2) Edit the pi.py so that the number of iterations is increased; i.e., change the for loop from range(50) to range(100). Now, rerun a redirection command to send the edited text to a new file that you can then compare to the previous file; what would this redirection command look like (after you've edited the script with something like nano)?
Show answer
Answer: Something similar to python3 pi.py > pi_100.out or ./pi.py > pi_100.out.
The > operator overwrites existing files/values by default! In our use-case we are planning to compare the results when changing the number of iterations in the Python scripts, therefore we need to save the output of the modified script to a different file to avoid overwriting the previous results. A variation on the redirection operator that appends textual output of a command to a text file (rather than overwriting it) is the >> operator.
You can use the wc command to check that the number of lines in the output file is as expected; e.g., wc -l pi_100.out would return the number of lines as 100.
3) Rename the file pi.out to pi_50.out.
Show answer
Answer: Use the mv pi.out pi_50.out command.
The mv command renames files and is also used for moving them from one location to another. Check the Moving and Copying commands section.
4) Use the command separator ; to run the following commands on the same command line: python3 pi.py > pi.out, wc -l pi.out, diff pi.out pi_100.out.
Show answer
Answer: python3 pi.py > pi.out; wc -l pi.out; diff pi.out pi_100.out
You can type as many commands as you like on the command line as long as you separate each of them with a semicolon ;. The ; is another useful special symbol also listed in the Special Symbols section.
If you have been following the previous tasks, the python3 pi.py > pi.out; wc -l pi.out; diff pi.out pi_100.out command returns 100 pi.out (the output of wc -l pi.out). The diff pi.out pi_100.out returns nothing because pi.out and pi_100.out are expected to be identical. The diff command compares two files and produces a list of the changes that would need to be made to the first file in order to make it match the second file. For more details check the diff command manual with diff --help.
5) Use the pipe character | to forward the textual output from the diff pi_100.out pi_50.out command directly into the less command as input.
Show answer
Answer: diff pi_100.out pi_50.out | less
The pipe character | is used to forward the textual output from one command (in this case diff pi_100.out pi_50.out) directly into another command as input; e.g., less is our example command of interest, the one to which we want to send the output. This would be equivalent to diff pi_100.out pi_50.out > temp.out; less temp.out. So, one can use the | to chain commands efficiently without temporary files.
Relative and absolute paths - more examples
1) Go to the ~/examples/ directory; i.e., cd ~/examples/, and run the python3 pi.py command. Which error is returned? Can you explain why?
Show answer
Answer: python3: can't open file 'pi.py': [Errno 2] No such file or directory. This is because the script pi.py is not in the examples directory.
You can run the ls command to check which files or directories are contained in the directory you are in.
2) How would you change the command python3 pi.py so that it can be run from the ~/examples/ directory?
Show answer
Answer: python3 ./python3/pi.py (i.e., run it with relative path).
You can navigate to the location where the file is, as done previously, or you can add the relative path to the file in your command. Most of the commands can work from outside the directory where the file of interest is located simply by providing the absolute or relative path. The easiest, and perhaps most often recommended choice, is to specify the relative path to the file. You can indicate the current directory with the ./ symbol, or as it is shown in the command prompt (e.g., ~/examples/).
3) How would you change the python3 pi.py command so that it can be run from any location?
Show answer
Answer: python3 /home/user/examples/python3/pi.py or python3 ~/examples/python3/pi.py (i.e., with an absolute path).
The command prompt tells you the absolute path of your working directory (the directory you are in). You can also use the pwd command to print the same information. More info about absolute and relative paths can be found in the Paths section.
The root directory of the filesystem
1) Why does the python3 /pi.py command return an error?
Show answer
Answer: It searches for the file starting from /, which is the symbol for the root directory of the filesystem. The file pi.py doesn't actually exist at that location (i.e., immediately under the root directory).
You can find an example of a hierarchical tree structure of a filesystem in the Structure section.
2) So far we have been working inside the /home directory; can you name any other directory listed by the command ls /?
Show answer
Answer: Some familiar directories/locations you will see in many filesystems are /bin/ and /var/.
As an example, /bin/ includes essential system libraries that are needed for all users; e.g., mv, ls, less (hint: type ls -l /bin/ls). There are many other directories/locations you'll find across operating systems. It's important to remember: not all locations in the filesystem are safe to freely alter. This is also why the root directory belongs to the root user. Importantly, remember that when you have superuser privileges you can freely alter all files; beware that changing files in certain locations can lead to operating system failure or corruption. The directories in / are common to many filesystems because they are related to how a computer's operating system is structured: kernel, system libraries (like ls already available at user's login), and user software. Read more about this structure in the Inputting Commands section.