Skip to content

Latest commit

 

History

History
286 lines (167 loc) · 12 KB

exercise-2.md

File metadata and controls

286 lines (167 loc) · 12 KB

Exercise 2 - Basics of the shell

You will learn to:

  • Understand how the command line works
  • Navigate through files and directories using a shell
  • Use the clipboard
  • Understand what commands are
  • Understand how variables work

📖 Check out the main page where we've listed some of the most commonly used commands (Helpful resources section).


2.1 - The command prompt

📖 When you start a shell, a prompt appears on the screen where the user can type text input. This prompt is also called a command line or commmand prompt. On most systems the prompt has a $ to denote where the command prompt is on the screen:

$

📖 Pressing Enter will tell the shell to execute the input. If the input generates some output, it's displayed under the command line:

$ ls
<output is displayed here>

2.2 - Commands and programs

📖 On Unix-like operating systems (like Linux and macOS) the commands you can execute using the shell (like ls, mkdir, cd, etc.) are small programs, not a part of the shell itself. What commands are available depends on the OS and what the user has installed.

📖 To make things easier, Unix-like OS-es come with a standard set of programs or commands called POSIX commands.

Here is a list of standard commands.

2.2.1 - Your first command

✏️ Start by opening your terminal application.

macOS Catalina users: The default shell in macOS Catalina is set to zsh (not bash). This means that after you open Terminal, you will need to start bash by typing bash and then pressing Enter. Alternatively, you can set the default shell to bash by following this guide. Use the echo $SHELL command to list what shell you currently are using.

✏️ Try listing the contents of a folder using the ls <foldername> command.

📖 The shell in itself is also a command, like other commands :)

✏️ Try starting a new shell process by typing bash and then pressing Enter:

$ bash
...
$

📖 Note that the result is a new command prompt for a new shell. This new shell is a child process of the first shell. To exit the child shell process and return to the first shell, use the exit command:

$ exit
exit
$

2.2.2 - General syntax for commands

📖 All commands in Unix-like systems follow a basic syntax:

  • <command>
  • <command> <argument>
  • <command> -<parameter>
  • <command> -<parameter> <argument>

An example:

cp -R dir1/ dir2/ - copy all files and subdirectories from dir1 into dir2

  • cp is the command
  • -R is a parameter - in the context of cp it means copy recursively (copy all files and subfolders).
  • dir1/ is a argument - In the context of cp it's the source directory
  • dir2/ is a argument - In the context of cp it's the target folder

Parameters are always prefixed with a - (sometimes they have an alternative "long" human-readable form style syntax with a -- prefix, like --count instead of -c).

What parameters and arguments a command takes, and if they are mandatory or not depends on the command.

✏️ The ls command has an optional parameter called -l, which changes the output of the command to a more detailed "long form". Try using this parameter to list out the contents of a directory.

2.3 - Files and directories

These first tasks are all about getting comfortable in your terminal, and execute some common commands.

✏️ Print the path to the current working directory

✏️ List the hidden files (if any) in a directory (hint: in unix, hidden files starts with dot (".ssh"))

✏️ Navigate to your local clone of this repository (hint: use the "code"-button in the GitHub-repository for this workshop, if you haven't already, to get the url)

✏️ List all .txt files in the files directory with human-readable size references ordered by the last-modified date.

Hint: See the help documentation for the ls command's l, t, r, and h parameters.

✏️ Locate the file called iterm.png by using the find command.

2.4 - Environment variables and $PATH

📖 How does the shell know what directories to search for to locate executable programs? Searching the whole filesystem would be very slow and inefficient. Therefore, to locate a program, the shell reads the locations from a special configuration value called the PATH variable, or $PATH.

📖 The value of $PATH consists of one or more directories separated by a colon:

/some/dir:/another/dir:/a/third/dir

📖 The shell searches through all directories in the $PATH to locate the program you are trying to execute. If you have two executable files sharing the same name located in two different directories, the shell will run the file that is in the directory that comes first in the $PATH.

✏️ List the contents of your PATH variable using the echo command.

📖 Note that you have several different directories in your $PATH in addition to the standard directories we mentioned earlier.

2.4.1 - Shell variables

📖 Shell variables are variables with name and a value used by the shell and other programs.

Variables have the following format:

KEY=value
KEY="Some other value"
KEY=value1:value2

💡 To define a new variable, try defining TEST=123 (note: no spaces before or after =):

$ TEST=123
$

Note that assiging a value to a variable will not generate any output.

💡 To show the value of a variable, you can use the echo-command. References to variables need a $ prefix:

$ echo $TEST
123

✏️ Try assigning a new value to the TEST-variable, and show the new value.

Note that overwriting variables is no different than creating new variables.

✏️ Try closing the terminal, and open it again. Then try echoing out the value of TEST again.

❓ The TEST variable now has no value. Why is this?

📖 Shell variables will be lost when the shell process is exited.

❓ But if $PATH is a shell variable and variable values are lost when exiting the shell, how is $PATH defined each time you open a new shell?

📖 When the bash shell starts up, it runs a set of special configuration scripts which defines the value of $PATH for every user on the computer.

📖 Each user on the computer can override any setting in the global configuration by creating a file called .bashrc in the user's home folder. In some OSes this file is already present by default. This file can be used to define or redefine any variable that the user wants to be set at startup, for example the $PATH. This is very useful for scripting, as we will see in the next exercise.

2.4.2 - Environment variables

📖 Environment variables are variables that are available to all subprocesses of a shell, not just the current shell.

✏️ Try defining a shell variable and open up a new child shell using the bash command. Then echoing out the value of the shell variable you previously defined in the parent shell.

Notice that the variable has no value.

✏️ Exit out of the child shell using exit.

✏️ To create a environment variable from a shell variable, first define the variable and then use the export command:

$ MYVAR=TEST123
$ export MYVAR

You can do this in one line as well: export MYVAR=1TEST123.

✏️ Try opening up a child shell again and echo out the value of your new environment variable.

📖 The child shell (and any other child processes or scripts) inherits the environment variables from the parent shell.

2.5 - Using the clipboard in the terminal

📖 Most users are already familiar with the cut, copy and paste shortcuts, but here is a reminder anyway:

Command Windows shortcut Linux shortcut macOS shortcut
Cut CTRL+X CTRL+X ⌘+X
Copy CTRL+C CTRL+C ⌘+C
Paste CTRL+V CTRL+V ⌘+V

📖 Depending on the OS and terminal settings, you may find that these shortcuts are not working as expected inside the terminal.

📖 In Linux you may for instance see ^V outputed if you try to paste some text into the terminal window. The short answer is that this is because the CTRL key has a special meaning in terminals, used to send signals to the terminal (terminate current program, etc.). They therefore sometimes collide with CTRL-based OS shortcuts.

Windows

Git Bash in Windows

📖 If you use Git Bash in Windows and haven't installed Windows Terminal, you need to go in to the Options menu and select "Keys", then check the box for "CTRL+Shift+letter shortcuts".

📖 You can now use Ctrl+Shift+C for copy and Ctrl+Shift+V for paste.

Windows Terminal

📖 If you are using Windows Terminal you can use the normal CTRL+C and CTRL+V shortcuts.

Linux

📖 If you are using the terminal application in Ubuntu you can use Ctrl+Shift+C for copy and Ctrl+Shift+V for paste. You can also right click on text with the cursor to select it.

Mac

📖 If you are using Mac you can use the normal ⌘+C and ⌘+V shortcuts.

2.6 - Basic command line navigation

📖 Moving around on the command line efficiently can save you a lot of time.

✏️ Try out these navigation shortcuts:

Previous command

Go to the previous command in the command history using arrow up and down:

Go to beginning / end

Quickly jump to the beginning or end of the text:

  • Ctrl + A - Go to beginning
  • Ctrl + E - Go to end

Move backwards / forwards one word

For a little more fine-grained movement, you can jump backwards or forwards one word at a time:

  • Alt + B or ALT + ← - Go back one word
  • Alt + F or ALT + → - Go forward one word

Search command history

Search backwards through command history:

  • CTRL+R and then type in a search term.
    • Press shortcut again to go to next search result (backwards in command history).
    • Press Enter to run command found in search.
    • Use left and right arrow keys to edit command found in search.
  • CTRL+G to cancel search.

Clear the screen

To clear the screen without clearing the current command:

  • CTRL+L

2.7 - Terminating processes

📖 Some times you need to terminate a running process if it hangs or if it does not respond to any user input. An example of this is a script with a endless loop. To terminate a running process we can send a signal to it. There are several differen types of signals that do different things, but the one we are interested in is called SIGINT (SIGnal INTerupt). There is a handy shortcut for sending this signal:

  • CTRL+C - Signals the current process to stop.

📖 We can try out this shortcut using the sleep command, which suspends execution for an interval of time.

✏️ Enter the command sleep 30 to sleep for 30 seconds.

✏️ While sleep is running, try stopping the process using CTRL+C.


Summary

In this exercise, we used some of the basic commands using our terminal and the bash shell. These are commonly used commands that we need to navigate and view the files of our system. Using a shell, you have the ability to automate your workflows by either creating useful scripts or gluing together different scripts and program in your system for maximum efficiency. In the next exercise, we will look into some of the things that make the shell effective - scripting.