Linux
Linux
NEWOUTLOOK.IT
Telegram Channel @nettrain
NEWOUTLOOK.IT
LINUX COMMAND LINE
An Admin Beginners Guide
While all attempts have been made to verify the information provided in this
publication, neither the author, nor the publisher assumes any responsibility for
errors, omissions, or contrary interpretations on the subject matter herein. This
book is for informational purposes only. The views expressed are those of the
author alone and should not be taken as expert instructions or commands. No
guarantees for earnings or any other results – of any kind – are being made by
the author or publisher, nor are any liabilities being assumed. The reader is
entirely responsible for his or her own actions.
Linux Overview
This chapter gives a brief overview of the Linux operating system, how it was
invented, what exactly open-source software means for you (the end-user), and
various types of Linux and how they may differ from each other.
Linux Shells
The shell provides one way for you to communicate with your machine via a
GUI or LUI interface. If you aren't familiar with these terms or want a quick
refresher, read this chapter.
IMPORTANT :
Chapter Summary
Linux is an open-source operating system developed in 1991. Linus
Torvolds is credited with creating the first functional Linux kernel that
was first ported to home computers and eventually distributed
worldwide. He is also one of the developers that started the tradition
Brief History
Once upon a time, computers were massive machines that took up a large part of
a room. They didn't have screens, keyboards, or mice; instead, users
communicated with them through manually feeding them instructions on paper
cards by using teletype machines or a series of switches. Even though these
machines were massive, they could only run one program and the program
instructions had to be re-fed to the machines every time they were turned on or a
new program was needed.
Someone realized that computers could do multiple tasks if they dedicated 30%
of the time to Paul, 30% of the time to Betty, and 40% of the time to Pat. The
computer could run Paul's program for 30 seconds then Betty's program for 30
seconds, then Pat's program for 40 seconds. One of the first multi-tasking
operating systems was named Unix. As discussed above, the method of
communicating with the operating system using a shell which evolved from the
old paper card programs.
Over time, computers started getting smaller but the concept of how to
communicate with them, along with a lot of the terminology carried over from
the early days stuck, including the idea of shells and terminals. Originally, the
terminal was a teletype that looked like a typewriter and display. The terminal
provided a more convenient way to feed information to a computer while the
shell provided a way to process the keyboard inputs.
Eventually, developers who wanted more user-friendly machines and to get
computers in the hands of more than just programmers created less complicated
operating systems where the work of the shell and its terminal could be hidden
from the user. Thus, operating systems with desktop environments were
developed.
Back to Shells
The Terminal
In Linux, the terminal is actually a terminal emulator. The user is usually unable
to communicate with the operating system without the use of the terminal, which
is partially due to security purposes.
Note that the shell itself is a program that receives input from the terminal or
GUI desktop - it is not the same thing as the terminal. Multiple terminals can be
used to communicate with the same shell. However, although a terminal can talk
to different variations of shells, it can only address 1 shell at a time.
The terminal is the screen that used to give the shell various commands. In
Linux, sometimes only a terminal CLI is available because the machine does not
need to run a desktop environment. This is okay for most computers and may
even be necessary for those that have limited memory or do not need to have a
screen the user can interact with.
Useful Commands
Other Shells
csh
The abbreviation csh stands for C Shell in Linux, or you may also get the
version called Tcsh . The C shell is an LUI interpreter with a C programming
language-like syntax. If you are not already familiar with the C programming
language, you may want to familiarize yourself with it before you attempt to do
any serious programming in a C shell.
Brief Overview of Shell Scripts
You can use either Bash or csh shells to run programs from a terminal. However,
this book will cover Bash shell scripting.
The difference is the latter of the two will accept inputs using C-like scripting
syntax. However, teaching C language is beyond the scope of this book, and may
make learning Linux seem complicated. For now, we will stick to the Bash shell
for Linux commands.
Chapter Summary
csh and Bash are both types of shells used in Linux.
csh, or C shell, is a type of shell that uses C-like syntax and scripting
language.
A terminal and a shell are not the same thing - a terminal is a program
used to allow the user to give instructions to the shell.
The root directory has many sub-directories. Without these files and directories,
certain programs and bits of hardware and software would not function at all on
the computer. Because everything is a file in Linux, it's not uncommon for
crucial parts of a program to be stored in separate folders.
It can also be difficult to find a file that you've downloaded if you don't know
where to look.
Let's begin by looking at the Linux file system, what certain folder names
represent, and where a downloaded file is likely to end up.
Picture a House
Think of the Linux Filesystem as a house. Different rooms in the house have
different functions. As we wander through the filesystem below, we'll also
describe a house to make it easier to remember its function.
root
The / represents the "root" of the filesystem.
The forward slash is a symbol representing the "root" or "main" directory. The
main directory should not contain any user files for optimum performance and
to prevent clutter. But some versions of Linux, such as Debian, allow a root user
to customize any parts of the program as he or she sees fit.
Ubuntu does not allow any single user automatic access to the / folder. Instead, it
requires that the user enter special commands to access its contents. This will be
covered in more detail later in this book, but that command is sudo, or "super
user do." Even if you have administrator privileges, if you are using an Ubuntu-
based system, you will have to enter sudo to execute commands that are only
supposed to be carried out by the root user.
The main part of the house is the Living Room. All the other rooms branch off of
the Living Room. The Linux Filesystem "Living Room" is the root directory. If
you were to search the filesystem hierarchy, you wouldn't find a file named
"root". The root folder is at the top in the picture above and is designated / . Like
root, the homeowner has to open the front door and invite the visitor in.
bin
The letters bin stand for "binary." This folder contains the built-in executable
programs that are normally executed.
The absolute path of this subdirectory is simply, /bin. As mentioned in the last
section, the /, or forward slash, represents the root directory, while bin is a
subdirectory inside of, or below, the root directory.
boot
This folder also contains boot-related files and it's best that the end-user not
tamper with the contents of this folder unless that user knows what he or she is
doing. In Linux, it is possible to put the operating system in a state where it will
not function properly. You typically won't spend much time in this directory.
In our Linux House, this is the sidewalk leading up to the house. The boot
directory leads you into the house just like the boot directory has the instructions
for starting up and getting you into Linux.
dev
Think of the abbreviation dev as standing for "device files." This folder contains
data for all of the essential devices installed on your system. Unlike Windows,
Linux device files are accessible by the root user, or admin, depending on what
permissions the user has. In some cases, the admin can even access the files
controlling the hard drive and other essential equipment.
The devices need kernel drivers to connect to the Linux kernel. Some Linux
kernel drivers also expose their interfaces to users through this directory. An
example is the older UARTs that print out the logs in Raspberry Pi and other
mini-computers.
In our Linux House, these are the appliances of the house. The stove, the
refrigerator, the washing machine, and the sinks and toilets are all available for
the family to use. The Linux kernel drivers are the electrical wiring and
plumbing connecting the appliances to the outside world. The Linux drivers are
hidden from view just like the wiring and plumbing are in the walls of the house.
Some drivers expose their interfaces through the dev directory just like a sink
exposes the water to the family.
etc
The etc folder contains configuration data for individual programs that are used
system-wide. This is not the same as the individual user's etc folder. If the user
has the proper permissions, they can hand-edit the data in these folders using a
home
Individual user folders are found in the home folder. On the Ubuntu Desktop, the
Download folder and Documents folder can be found under the home directory.
On a command line, it might look something like, /home/username. For
example, the command line would look like /home/kevin if the user's name
happens to be Kevin.
The home directory has a shortcut symbol which is the ~. We'll discuss it more
in the Linux Command Line sections but kevin can quickly jump to the home
directory by typing either cd ~ or cd /home/kevin.
In our Linux House, these are the bedrooms of the house. Kevin has his own
bedroom and Suzy has her own bedroom. They keep their private possessions in
their separate bedrooms. The bedroom is similar to the home directory. Each
user's personal setup is stored in the home directory. Each user can create and
add files to their home directory as they see fit just like each person can decorate
their bedroom.
lib
The Linux system library, which may look like /lib in the terminal as the direct
path, contains libraries shared by application programs that are necessary for
them to run. The libraries are needed for the application programs to run
properly.
In our Linux House, this is the pantry with the spices that are used for cooking.
The spices aren't used for every meal but they're available when they are needed.
The main ingredients were the programs in the /bin directory and to taste just
right, the spices in the pantry are needed.
media
The /media folder, or directory, contains subdirectories and subfolders where
removable devices that store media can be mounted. Without this directory,
devices such as USB drives and DVD ROMS might not work properly.
In our Linux House, this is the driveway to the house. Visitors to the house
(USB) must park in the driveway before making their way to the house.
How to Use:
mnt
The /mnt is referred to as the "mount" command. This command enables you to
mount and unmount files. The /mnt directory provides a place to mount more
permanent files such as the CD or DVD drive.
In our Linux House, this is the garage attached to the house. Permanent residents
of the house park in the garage instead of in the driveway.
opt
This directory holds software applications physically configured by the user or
administrator. You may find files for your desktop environment and other
software non-essential to the system here.
In our Linux House, this is the back patio. It provides some needed recreational
space but it isn't an important part of the house.
proc
The /proc directory holds many details about your Linux system. The files stored
here are referred to as "virtual" files because they don't actually exist on the disk.
If you have the proper permissions, you can still explore this directory to learn
more about the Linux system and programs on the computer you're running. It
may help to picture the files in the proc directory as nothing more than ghosts of
recently accessed files.
In our Linux House, this includes the thermostat, the water meter, and the
electrical usage meter. If you want to see what is going on in your house, you'd
check the thermostat to see what the temperature is, the water meter to see how
much water you are using, and the electrical meter to see how much electricity
you are currently using.
root
This is the home directory for the root user. Root is considered the highest level
of anything, so the root user is the highest level user on the computer.
In our Linux House, this is the master bedroom. When you're in the living room,
you're saying this is Jesse's house but when you're in Jesse's bedroom, that is
where his personal things are kept.
sys
The /sys directory stores temporary files with device information in a virtual file
system. This is very similar to the /proc directory and is basically a newer and
better-maintained version of the /proc directory. The /sys directory typically has
more ways to control device drivers while the /proc was typically for reading.
In our Linux House, this includes the thermostat and meters as well as the light
switches, faucets and circuit breakers. We can turn the water and electricity off
and on as desired.
tmp
This directory stores temporary files from applications and users. Do not store
anything important in the /tmp folder, as the contents may be regularly deleted
when a user logs off or the system is shut down.
In our Linux House, this is the trash can.
usr
Although it looks like an abbreviation for "user," it's not. It stands for "Universal
System Resources" or, on Unix, "Unix System Resources." Regardless, the /usr
directory still stores much of the information used by individual user accounts on
a Linux system, including binaries, header files, and documentation for the
binaries.
In our Linux House, this is the drawer that has all the user manuals and warranty
information for the appliances.
var
The /var folder contains files that the system writes data to while it's operating.
var is a high-level directory that is not shared over a network or with other
computers, and it contains some user information that is not read-only. This is
Quiz Time:
Take out your notebook and answer the following questions. Feel free to look at
an earlier part of the chapter if you think you need a reminder.
Chapter Summary
The Linux file system is like a hierarchy, with the top files being the
main parts of the directory and smaller, sub-directories underneath.
Linux stores everything as a file
Certain file directories complete certain tasks to avoid clutter or
confusion.
The /proc directory can tell you a lot of information about the
particular system.
The dollar sign, $, is used to denote user mode. It differs from the pound sign or
hashtag #, which is used to denote root user mode. Remember that you do not
get access to the root user directly in Ubuntu; you have to type in sudo, which is
the command to access the root directory, and then your command. We'll talk
Command Description
pwd Print Working Directory
cd Change Directory
clear Clear the terminal
ls List Directory
file File characteristics
mv Move a file or directory
cp Copy a file
mkdir Make Directory
rm Remove a file
rmdir Remove an empty directory
touch Create an empty file
cat Concatenate a file (dump contents of result)
echo Echo the contents to the terminal
less Display the contents of a file
head Display the first 20 lines of a file
tail Display the last 20 lines of a file
Command Options:
Sometimes you can add options to commands to make them do different things.
For example, you could add -b to your file command to display a brief version.
This may come in handy if all you want to know is the file type in brief mode.
When combining this command with options, use the syntax: file [option]
[filename]. For a complete list of options, see the man command, or manual
pages by typing man after the command (ie file man) into the terminal. You may
also be able to use the --help option such as ls --help
#
Explanation:
Linux systems may require you to enter very specific commands to receive the
results you want. The folder you are working in matters when determining
whether or not these commands are successful. A program isn't going to assume
you have access to anything other than your current folder. But sometimes you
may not be sure where you are and the pwd command lets you know where you
are. In this case, we're in one of the bedrooms of the Linux house.
#
cd
This command stands for "change directory." To change to a lower level
directory than the one you're already working in, type cd, press the Spacebar
and then type the name of the directory to move to. Let's say we're trying to
access a folder called "my_test" in the current directory. We would type cd
my_test, and then we would press Enter .
Explanation:
A lot is going on in the example above. We move into the my_test directory and
print the working directory to make sure we are where we think we are. The ".."
means the parent directory so the "cd .." takes us back to the home directory
where we came from. We then change into the root directory and confirm our
location. The - is used to take us back to the last directory we were in so the "cd -
" takes us back to the home directory.
A lot of tutorials on the internet about using the Linux command line may make
the process appear more complicated than it really is. A person new to using the
command line and unfamiliar with using relative commands may make the
mistake of typing out the full path every time he or she tries to execute a
command. You don't have to do this.
Remember that Linux uses a different kind of syntax than Windows. For
example, typing / before the folder name is like asking it to find a folder in root.
If the folder is not in root, you may receive an error message. Likewise, if you
try to find a folder in ~, or home, and the folder is not in that directory, you may
Example:
Let's go from your home, or ~, folder to your Desktop folder on the command
line. Just type cd Desktop into the command line and press Enter . You should
now see something like this:
Do you notice how the directory is different from when you were in your
Desktop folder?
Exercise:
Open the command line on your Linux device or virtual machine and type, ls.
This should bring up a list of files and folders on your device. Next, use the
"change directory" command. Type, cd, press the Spacebar , then type and the
name of a folder you would like access to. For this exercise, let's use, etc. To
ensure you've gone to the correct directory, use the pwd command, which will be
explained below.
clear
When you are typing commands into the terminal, it can often become quite
cluttered, especially if you've recently downloaded new software using the
command line. When the screen gets cluttered, it can make it harder to focus on
your next command. The cluttered commands can also get in the way of
commands you want to implement later. Although using Escape , Delete , and
Backspace will not work to remove your old commands, you don't necessarily
have to close the terminal and open a new one if all you want is to clear the
screen.
Just type, clear into the terminal after the $. The screen should clear itself, and
you should be able to resume typing commands onto the screen.
ls
You can use the ls, or "list" command, to display files in the current working
directory. Remember that the current working directory is the directory on your
current command line that you are working with. As you move into a new
directory, that becomes your current working directory.
Type ls to have a list of files generated. The ls by itself command lists all the
files in the current directory. However, if you put a path after the ls, you can list
the files in any directory.
Type ls / to see the files in the root directory or ls /etc/systemd to see the files in
the /etc/systemd directory
Example:
Example:
Example:
file
Use this command to have your computer tell you a file's type. All you have to
do is enter the file followed by the name of the file of which you want to know
the type. The file command can be helpful when you aren't sure how to handle a
specific file. Let's say you've saved several different kinds of files under the
same name (my_name.png, my_name.txt, and my_name.pdf), or you need to
help rewrite a specific file on the system, but you aren't sure what kind of file it
Example:
Explanation:
The file command tells us the textfile.txt file has ASCII text which is just text
like you are reading. However, the cd command used to change directories is a
shell script made from ASCII text which is executable. As discussed in the
Linux Basic File Directory chapter, the /bin directory is the kitchen and holds the
common Linux command line programs we'll be running.
You can also use this command to find all of the files in your current working
directory by typing file *. The asterisk, *, signals to the machine that you want it
to show you the file characteristics of everything that Linux considers a file in
the current directory.
Example:
Let's say you want to move a file called "photos.png" to my home Desktop
directory. All you would need to do is type the following into the terminal:
cp
When you type cp into the terminal, it stands for "copy file." In a sense, this
command is used similarly to the mv command. To make a copy of a file with a
new filename in the same directory, you would simply need to type cp and the
name of the current file, then the name of the new file you want to copy to.
When copying directories, you may receive a message saying you need to put an
-r after cp to copy the files or directories. The -r is for recursive and indicates
you want to copy the directory and all the contents inside the directory.
Example:
First, we’ll figure out where we are. Use the pwd to find out where we are.
But what about copying a complete directory? Can we just copy a directory the
same way?
mkdir
We look at the Desktop directory and then we created a new directory in the
Desktop directory. We confirmed the new directory with the ls command.
Now let’s try moving a file into the new directory
#
rm
We created a new directory named Desktop3. Why? So that we can delete it, of
But this acts the same as the copy command. The directory can’t be deleted if it
still has files in it. Remember how we copied the entire directory and files last
time?
Yes, we need to use the -r command to recursively delete the files inside the
directory as well as the my_photos directory.
We created a new directory named Desktop3. Why? So that we can delete it, of
course.
Now that the directory is empty, we can use the rmdir command.
Sure enough, the Desktop3 directory is now gone after running the rmdir
command.
The rmdir command may come in handy if you create a file in a directory that
you no longer need and it's inconvenient or not possible to remove the file using
the desktop. As mentioned earlier, not all Linux systems have desktop
We know what the current directory looks like. How can we create a new empty
file?
Exercise:
Create two empty text files using the touch command. Place them on your
Desktop.
#
echo
Use the echo command when you want to echo a string of text. Just type echo
and write the message you want to say in quotation marks. For example, echo,
"hello world" would print out "hello world" to the screen on the terminal. This
may come in handy if you are programming and want to leave personalized
instructions to whoever uses the terminal next.
Example:
Let’s try using the echo command.
Well, that doesn’t do much, does it? It just printed out a string – just like if we’d
typed it.
Can we do something useful with it? How about creating a file with a greeting
inside?
The hello.txt file has “Hi Linux CLI experimenter” in it – just as if you’d typed
it into Notepad or a text editor.
Exercise:
Use the echo command to print "hello world" to the screen.
Pair the echo command with the * command and print a list of your current files
and directories in your home folder. Record your findings in your notebook.
Using the options you know of now, create a new command using the echo
cat
To concatenate means to link multiple things together. You can combine multiple
files by entering the cat command. A nice side-effect of the cat command is that
it prints out the results of the concatenation operation on the screen. Just type,
cat and the name of the file to view the contents of the file in the terminal.
You can do quite a bit with this command, including creating new files, viewing
the contents of multiple files, displaying the output of a file, copying the
contents of one file to another file, and appending the contents of one file to
another.
We sent the contents of the hello.txt file to the output display 3 times. Just to
verify that hello.txt didn’t change, we cat it by itself again.
But if we send the resulting output to a file, cat is an even more useful
command. To do this, we use the > symbol along with the name of the file. The
> filename means send the output into a file instead of displaying it on the
screen.
Notice that there is no output on the screen when it is redirected to the file. I cat
the original file - it is the same and then I cat hello3.txt and see the 3 copies of
the string.
Exercise:
With this exercise, we will practice using the cat command to create new files at
the command line, read those files, and merge them into one new document.
To complete this exercise, you may need a Linux operating system with a
desktop environment installed.
Change directories to your desktop environment and use the echo and cat
commands to create a new file. Create another new file with the cat command.
Write whatever you want in this file as well.
Now cat both files so you can see their contents on the terminal. Once you've
done that, use the cat command again to create a new file by merging the
contents of the old files and redirecting the output to the new file.
Record your findings in your notebook after you complete the exercise. Use the
rm command to get rid of the files you created if you have no other use for
them.
less
Exercise:
Go online and copy some Lorem Ipsum text or write a long document. View its
contents using the cat command and notice how it scrolls past very fast. Then try
using less to view it.
Also, try adding a / and using the search option. Record your findings in your
notebook.
head
If you want to see the beginning of a specific file, the head command is what
you're looking for. Typing in head and the name of the file that you want to be
read will result in the first ten lines of the file's content being printed out onto the
screen of the terminal.
The head command shows the first ten lines of the contents of a specific file by
default, and you can adjust it using the -n option and specifying a number. For
example, let's pretend that you have a text file with over 700,000 lines of code,
but you only need the first 17 lines. You can use the head command with -n 17
and the filename to retrieve that information without having to open the entire
file with all 700,000 lines of code.
The head command helps reduce clutter if you decide to read a large file and
you already know that the information you need is at the beginning of the file.
For instance, the title of a document is probably one of the first lines in the file
Many times, we want to see a smaller number of lines and we can use the -n
option along with the head command where n is the number of lines to show.
Let’s try displaying on the first 5 lines.
tail
Like the head command, the tail command displays a certain number of lines
from a file as standard output but is the opposite of the head command. The tail
command returns the last ten lines of a document or other file by default. Its
usage is similar to the head command and you can use the -n option.
To use this command, type tail and the name or the file or directory that you
want it to read and display.
For example, imagine that you only need the code in the last five lines of a long
and complicated file. Type tail and the name of the file. Like the head command,
you can also alter the number of lines it prints out using the -n option.
Explanation:
Like the head command, the tail command has a range of uses, though it mostly
serves as a means of helping you quickly find important information. It can
become tedious to print a long file to the terminal and scan through it manually
for things like coding errors, update problems, or other inconsistencies.
Many times, the error in a log file will be at the end so the tail command is
perfect for seeing what caused an error.
Exercise:
Go back to the document you created in the previous exercise and use the tail
command and the -n option to print out only the last five lines of your document.
Experiment with the -c option. Type -c and a number and see what happens.
Record your findings in your notebook.
vim
Typing vim will also allow you to use a text editor in the terminal. The
abbreviation vim stands for "vi improved" in Linux, and it offers a few features
not found in previous versions of the vi text editor.
vimtutor
This section will provide an overview of the vi and vim editors but a vim tutorial
is built into most Linux distributions and can be viewed by typing vimtutor. The
tutorial will take less than an hour and has been helping people learn to use vi
and vim for many years.
vi/vim Basics
The vi/vim editor has 3 modes, command mode, insert mode, and visual mode.
Command Mode - This is the default mode and lets you move around
in the editor, exit the editor, and search for text. Press the Escape key
to return to Command Mode from the other modes.
Insert Mode - This mode lets you insert text into the document. To get
into this mode, you first need to be in Command Mode and then press
the i key to enter Insert Mode. Press the Escape key at any time to
exit Insert Mode.
Visual Mode - This mode is used for selecting text in the document.
To get into this mode, you first need to be in Command Mode and
then press the v key to enter Visual Mode. Press the Escape key at
any time to exit Visual Mode.
Quitting vi or vim
Exercise:
Open vim by typing vim and the name of the file you want to edit. For this
exercise, we will edit that file we were working on in the previous example. You
should be able to use the arrow keys to move the cursor to where you want to
begin editing. Press i and then the Enter or Return key to enable editing. Add a
sentence such as "I'm using vim" to this document. Next, save the document.
Press Escape to go back into "Command" mode, then type “:q” to quit. It may
take a few tries before you feel comfortable using the editor and entering the key
combinations.
More vim
Other things you can do with vim include viewing and editing two documents or
files at once, copying, and pasting.
Vertical Split
To view two documents or files at once, type in vsplit and the name of the file. In
some cases, you may have to type in the absolute path. Once you do this, you
can now view and edit both documents. This may come in handy if you are
editing a file's code and you need certain lines of the two to match.
Copying
If you want to copy text in vim, enter Visual mode and select the text and type y
(short for yank). Make sure you are in Visual mode, or this may not work.
Cutting
If you want to cut text in vim, enter Visual mode and select the text and type "d."
Make sure you are in Visual mode or this may not work.
Pasting
To paste, type p. Make sure you are in Visual mode or this may not work. The
program should let you know what mode it's in by displaying it at the bottom.
Exercise:
Practice opening up two files at once and edit them to say the same thing. Then
Chapter Summary
In this chapter, we covered some basic commands, including
commands that may help you change directories, list the files in a
directory, view the path of the directory you are currently working in,
clear the screen of text and already executed commands, view a file's
type, move files, remove files, remove empty and full directories,
create blank files, concatenate files, print file contents to the screen of
your terminal, and view a set number of lines or bytes in a file.
Command Description
locate Locate file
find Find file or files
grep Global Regular Expression Parser
tar Tape Archive
gzip Zip compresssion
zcat Read contents of Zip file
wc Word Count
history Display command History
tree Show Tree representation
alias Create a shortcode for a command
curl Download a file
cmp Compare
diff Difference between files
which Which command executes
ping See if anyone out there
man Manual
help Help on command
Exercise:
Use the star wildcard * to find every instance of a file containing a certain word
in your Desktop folder.
Try using the question mark wildcard ? to find every instance of a file with a
certain number of letters.
Use the square brackets wildcard [ ] to find every instance of a file that starts
with the letter "a."
Pair these three wildcards with three commands you learned in this chapter.
Record your findings in your notebook.
#
locate
To use the locate command to find a file, type locate and the name of the file
you want to find; then, press Enter . The search results should list the directory
and path in which the file is found.
Example:
Let's pretend you are searching for a file that you named "codewords2019.txt",
but you can't find all of them. Using the locate command should find that file for
you while also giving you their directory path, so you can access and modify it
without looking through a bunch of unrelated files.
Explanation:
The locate command helps you find instances of a file name and may be useful
if you have multiple files of the same name and do not know how to access
them. Using it will result in a list of files that contain your keywords and the
paths associated with the listed files.
Exercise:
Create a file or search for one already created using the locate command. Record
your findings in your notebook.
find
The find command can be used like the ls command to search for all files in the
current working directory. Just type find and no other arguments. You can also
type in the direct path if you want to have it list other files in another directory.
It can also be used for other things, such as what the next few sections will
cover.
Will find all the files named "my_filename.txt" in the root directory. This
command becomes very powerful when paired with wildcards.
This command can also be used to search for files of a specific type. Type find -
name "*.[the type of file you want to be found]".
For example, if you want to see all of the ".jpg" files in the current directory and
subdirectories, you would type, find . -name "*.jpg" and Enter
You can also use this command when searching for files that are not of a certain
type. For example, if you entered find . -not -name "*.jpg", you would get a list
Exercise:
Use the find command to locate a list of files of a specific type. Write down the
file you want to use in the next part of this exercise, then copy the absolute path
of the file in case you need to enter it.
Next, search for that specific file. Was Linux able to find it? Record your
findings in your notebook.
grep
The grep command is the global regular expression parser and it looks for a
pattern in a file. To use it, type grep followed by the command or string you
want to find, as well as the location you want it to search for the command or
string.
For instance, if you wanted to find all files in a particular directory starting with
a specific word or letter, you could use the grep command by typing “grep
[name of the file you want to find] [name of the directory where you want to find
it]”.
If you wanted to find user information for a user named James, you could type
something like the following and get the resulting print out.
Explanation:
grep stands for "global regular expression parser," and the name comes from
when software was simple and one of its main concerns was saving space.
Exercise:
Use grep to search for a word. In this scenario, we will be searching for every
file with the word "photos." Type grep -w "photos" file, then search for a file
you have that starts with a certain word using the "grep " command. If you don't
Explanation:
The tar command helps you save space, which can come in handy if you have a
computer or network with limited storage space due to usage as a server or
multi-user machine or network.
Exercise:
Create a new file using the touch command, then change it into a .tar file.
gzip
The gzip command zips a file, and you can use the gzip command in a similar
way to the tar command. Like tar, it is used to compress or expand files. To use
this feature, type gzip and the filename into the terminal, then press Enter .
By default, the gzip command deletes the original file once it creates the zipped
version. You can prevent this, however, by typing -k before the filename. For
example, if you did not want Linux to delete the original file, you could type
“gzip -k filename”.
Exercise:
zcat
If you want to read files that were gzipped without unzipping them and
potentially wasting time and space in the process, you can use the zcat
command. This command will allow you to read gzipped files from the terminal.
To use it, type zcat and the name of the gzipped file you want to have a look at.
Then, press Enter .
If you've done this correctly, you should be able to view the contents of the file
from the terminal without having to uncompress the file.
Exercise:
Read a zipped text file without unzipping it first using the zcat command.
Useful Commands
wc
The wc , or "word count," command counts the number of words, letters, and
lines of the information it is told to count. To use it, you would type wc and the
name of the file or directory in which you want the word count performed.
For example, let's say we wanted to get the word count of file1.txt. We could
type “wc file1.txt”. The results should give us three numbers--the first is the
number of lines, the second is the number of words, and the third is the number
of bytes. If you only wanted to know one of these things, you could use other
options.
We can also get the number of lines by typing “wc -l file.1.txt”.
Replacing the -l in the previous example with a -w will give you just the word
Exercise:
Find the word count, number of lines, and number of bytes of a file of your
choice. Try to use a different file than the ones you've used for previous
exercises.
Compare the word count of two different files, then write your findings in your
notebook.
history
Linux allows you to view the commands that have been typed in the terminal
previously. Type history and press Enter to see the command history . By
default, Linux will list the last 500 commands you typed into the terminal. You
can even combine this command with other commands, such as the tail
command, to make it more useful.
Sometimes you may need a reminder of how exactly to write a command.
Instead of looking them up all the time or memorizing them, you can use Linux's
built-in features to make that process much easier. Some commands, such as the
help command, the man command, and the history command, all fall into this
category.
Entering the history command allows you to view the past 500 commands you
entered into the terminal, which will come in handy if you don't remember
exactly what you typed and don't want to or can't afford to waste time looking it
up on the Internet.
You can also find recent commands by pressing the Up arrow key .
tree
Do you remember using the tree command earlier in this book? You can use the
tree command if you want to know what subdirectories and files are contained in
the folder in which you are working. Type tree into the command line, then
press Enter .
This may remind you of the ls command, but it is much more detailed, as it
shows not only each folder a directory contains but also each program file
contained inside those folders as well.
Exercise:
Use the tree command to generate a detailed list of files and folders in your
current working directory. Then, do the same thing using the ls command. Write
how they are different in your notebook. What might you use the ls command for
that you would not use the tree command for? What might you use the tree
command for that you couldn't use the list command for?
Example:
A common alias is ll which will call the ls -al to show all files in long-form.
Don't worry about messing anything up; your custom commands will not be
available in your next session unless you edit your shell configuration profile.
You can look up how to edit your shell configuration profile, but make sure you
are well versed in Linux programming and commands before you do that, as it is
not a task that is recommended for beginners.
It is possible to mess a few things up when creating custom commands, so be
Exercise:
Create three custom commands and then run them. Record your findings in your
notebook. What were your commands, and what did they help you do? What
potential uses do you see for setting aliases in the future?
curl
The curl command can be used to download files from the internet using the
terminal in the absence of a GUI. To use this command, type curl, the option that
you want the machine to perform, and the URL of the information you want to
retrieve. You can also use the curl command to upload files to the Internet.
Example:
If you wanted to download a picture of the Biggest Ball of Twine using the curl
command, you would enter
Doing so would download a file of the same name as the file you typed in.
If you want to use curl to view the content of a website, type curl [site whose
file content you want to view]. The result should be the HTTP source code.
To upload a file, you can type "curl [file] [upload address]." For example, if I
wanted to upload a file called "photos" to a local server called "server," I might
type,
diff
The diff command compares two similar files and prints out the parts that are
different, making changing the files to where they are identical much easier. This
command is easy to use -- just open your Linux terminal and type diff, then the
name of the two files you want to be compared, separated by a space. For
example, you can type diff file1 file2
cmp
If you want to compare two files byte by byte, you can use the cmp command.
Unlike the diff command, this command will print out which bytes and line
numbers are different in the files being compared.
Exercise:
Practice using the diff and cmp commands.
For the diff exercise:
Open a word processing program on the GUI and make a short list of items.
Then, save it as a .txt file and copy the list. Paste it in another document on the
word processing program and change one word. Name these files something
recognizable, and then go back to the terminal.
Example:
Document 1 Document 2
1. 1.
Rosemary Rosemary
Type diff into the terminal and enter the names of the two files you created. The
results should print to the screen at the terminal. Record your findings in your
notebook.
For the cmp exercise:
Open another word processing document on the GUI and make two documents,
each with a shortlist of the same items. This time, don't change any of the text in
one of the documents except for one number on the list. You should have two
nearly identical documents, except one with a different number on the list.
Example:
Document 1 Document 2
1. 1.
Rosemary Rosemary
2.
1. Curry
Curry
which
The Linux which command can aid you in locating where your important
programs are installed by providing the absolute path of the file. To use this
command, type which , followed by the name of the program you want to find.
For example, if you are looking for the path and directory where the executable
file for the internet browser "Firefox" is stored, you would type “which firefox”
and press the Enter key in the terminal.
Exercise:
Use the which command to locate a file you created in a previous exercise, then
write down the results in your notebook.
ping
The ping command lets you check whether or not a remote host is responding.
Just type in ping , followed by the URL of the website you are trying to reach.
For example, if you wanted to ping Google, you would type, ping
www.google.com.
Exercises:
ping a website of your choice. Use the Ctrl+c keyboard shortcut to escape the
loop, then record your findings.
Help Commands
man
If you type in man in the terminal followed by the command you want to be
described, you'll get a list of uses for the command. For example, if you typed
man touch, you would get a list of uses for the touch command. This comes in
handy if you need to know what a command is in a pinch and don't have time to
look it up.
Typing man for the manual page command will give you a lot more information
Exercise:
Look up the man vim command by typing “man vim” at a command prompt.
You should get something like below:
Chapter Summary
In this chapter, we covered more advanced Linux commands,
including searching using the locate, which, and find commands. We
also learned about the grep command; how to find the word count,
line count, number of bytes; and how to use wildcards.
We also covered other useful commands, such as zipping files, history,
tree, alias, curl, diff, cmp, and pinging.
We also covered some helpful commands, including man and the help
commands.
Command Description
df Display filesystem space
du Disk usage
free Free memory usage display
w Which users are logged in?
whoami Whoami logged in as?
hostname List the hostname of the machine
uname Print kernel information
quota Quotas and limits of users
passwd Set/change a users password
chage Force user to change password
adduser Add new user
usermod Modify a user
addgroup Add a new group
userdel Delete user
delgroup Delete a group
df
The df command stands for "display file" or "file system space" and allows you
to display file system space that is being used and is available. To use it, all you
have to do is type df and the folder name. If you only type df, an overview as
shown below is given.
du
The du command is the "disk usage command," which allows you to see disk
utilization for files and commands. To use this command, type du followed by
the directory. This command may come in handy if you need to recycle data
space used by a program, although it may give you a rounded up estimate
instead of actual, real-time usage.
A common way to type this is “du -ch” which gives a summary (the -c) and
human-readable output (the -h) which append the K for Kilobytes, M for
free
Use the free command to find out how much memory and system RAM is
available. This may come in handy if you need to know if a program is eating up
system resources or how much memory a program is using.
whoami
The whoami command quickly shows you which username and account you are
logged in as. This may prove helpful if you are not sure what permissions your
user account has and what commands you have the authority to run. It could also
help you if you are logging yourself into different accounts with different
permissions while testing features on the system.
To use this command, type whoami into the terminal and press Enter . You
should see a readout with your username.
hostname
You can use the hostname command to find out the name of the host. You can
also use it to print out the IP address with the -i option. In the result below, the ip
address of 127.0.0.1 indicates a localhost meaning "this computer".
uname
This will give you a printout of information about the operating system and the
machine it is installed on. Use the -a option to see all the kernel information
including build date kernel version info.
quota
Without a set data quota, users on a network could hog all the resources for
themselves. They could start downloading unnecessary files and keeping bit and
pieces of information, such as reports, instructional videos, and projects on their
accounts as if it were their home machine, while not considering the needs of
other users or the operating system.
With the quota command, limits for the user can easily be monitored. This
command displays the user's disk usage and limits, and a user with administrator
privileges can use this command to view the quotas of other users. To use this
command, type, quota -s and the user ID of the user whose quota you want to
check.
Editing Quotas
If you want to change the quota of a user or group, you can use the edquota
command by typing edquota -u and a username or ID to edit the quota of an
individual user. To edit the quota of a whole group, type edquota -g and the
group name or group ID.
#
passwd
As mentioned previously, users with administrative privileges can do a lot with
Linux if they know how. The following are a few more things you might have to
do if your job grants you root user privileges.
Let's imagine that someone at work forgets his or her password. If you are the IT
There may also be situations in which the user will need to change his or her
password but has not changed it yet. In this case, you may want to execute a
command that will force a user to change his or her password (see the chage
command below).
The passwd command is used to change a user's password. This command can
only be used by someone with administrator access. An administrator can also
use it with other options to do a variety of other things, such as -w to warn a user
before their password expires, or the -n option to set the minimum number of
days a user must wait before changing his or her password.
Exercise:
Experiment with the passwd command and its options. Log in as the target user
to test and write your findings in your notebook.
chage
The chage command can be used in Linux to force a user to change a password
by typing “chage -d 0 <username>”. Like the setting in the previous example,
this command will also force the user to change his or her password upon next
login.
If you want to make it so the user who refuses to change his or her password will
be locked out of his or her account, use the -E option with the chage command
instead. It should look something like chage -E <date or days until expiration>
<username>. This will lock the user out of his or her account until he or she has
it reset by an administrator or root user.
These features are important because they can serve to automatically enforce
policies your company may have about users changing their passwords, so
important information is not compromised.
Exercise:
adduser
The adduser command can be used to create and add new users. Type, adduser
and the username you want the new user to have to create a new user.
Adding a Normal User
To add a normal user, type adduser and the username you want the new user to
have. The user will automatically be assigned an ID number and granted all the
privileges a normal user on the system has.
System users are placed in the nogroup group by default, but you can edit a
system user's group ID with the gid option.
Exercise:
Create a new user using the adduser command. You can delete this user account
using the deluser command later, or you can keep the account for future
exercises in this chapter and extra practice.
#
usermod
Another powerful command you might find yourself needing to use as an admin
is the usermod command. Use this command to change various details about a
user's account, including their group IDs, whether or not the user's account is
active, and a few other things.
Lock/Unlock
One thing you can do with the usermod command is "lock" and "unlock" user
accounts. Let's pretend that you need to lock a user's account because he or she
no longer uses that account. Simply type usermod -L to lock the account and
usermod -U whenever you are ready to unlock the account.
Expiry Date
addgroup
The addgroup command is similar to the adduser command, except users who
belong to a group can share documents and files and may have access to certain
permissions and files that the rest of the users don't. It can also be a way to
evenly set permissions for some users.
For example, let's pretend you have a group called "employees." Everyone added
to the employee group can access project files and the chat feature to
communicate with their teammates, but they do not have administrator rights and
cannot go into the system and change crucial settings, re-assign programs to new
directories, change others' passwords, allot themselves more data, among other
things.
Exercise:
Create a new user using the adduser command. Then, create a new group using
the addgroup command. Place the new user in the group, then remove the group
and the user.
Exercise:
Practice all the commands covered in this chapter and pair them with some of
the mentioned options. Record all your findings in your notebook.
Generate a list of questions for further study based on your list, then record
where or how you think you can gather this information.
Chapter Summary
In this chapter, we went over:
Normal Users
User accounts are the accounts that belong to people who are authorized to use
the machine but may not have all the access an administrator has. A typical
person can have access to a Linux machine as a user and not have full
administrator privileges. The user can perform the tasks he or she is authorized
to do while minimizing the chances that they will mess up the operating system.
Exercise:
Explain how a root user is different from other users. Write your answers in your
notebook before going on to the next section.
sudo
In Ubuntu, users may need to use a special command called sudo to gain root
user access to certain files or privileges, such as downloading files or making
major changes to the operating system.
As explained earlier in this book, sudo is short for "super user do."
In Ubuntu Linux, users are not in root user mode. For example, you may not be
able to read or change some of the files in the root directory. The extra step of
typing sudo in front of the command is one extra safeguard against accidentally
damaging or deleting something important.
If you run into anything like this, you can try to use the sudo command to get
access and run programs as the root user or administrator. Without typing sudo,
you may not have the necessary permissions to run programs that only have
administrator privileges and you may not be able to download files. See the
example below to see how adduser on Ubuntu needs a sudo prefix.
rwx
In Linux, rwx stands for "read, write, execute."
Yes, the problem is that it doesn't have execute permissions. So let's give execute
permissions to ourselves and our group.
Exercise:
Change one of the document files you created for an earlier exercise to "read-
only" using the chmod command. If you aren't sure how to do this or receive an
error message, make at least three attempts and record your findings each time.
In the example above, the user root and group root were not allowed but you get
the idea.
Exercise:
Change the ownership of a list you created in a prior exercise, so you do not
have permission to access it via the terminal. Write down the steps you took.
#
setuid
Programs and scripts usually run with the permissions of the user id and group
id. The setuid command allows someone to set the user ID or assign its
privileges to another user. For example, if you wanted a program with normal
user access to be run with admin access, the setuid command would be used.
Be very careful when using this command because it can cause security issues
by circumventing the natural segmentation that Linux provides us.
How can you tell when setuid has been set? Look for the s in the place the x
should be in the user field.
setgid
setgid can be read as "set group id," and is similar to the setuid label but for the
group privileges and it covers both directories and files.
#
/etc/passwd
This is not the directory where individual user passwords are kept; rather, it is
where user accounts are defined. You can find the user's username and user
account's ID number through this directory, and you can also find the account's
group ID number here. In some cases, you can also access the user's full name,
home directory, and the location of their default shell.
Passwords, along with other important user and system login information, are
kept in /etc/shadow. Even though it might be tempting to try to edit some of
these files manually, it's best not to. As mentioned earlier, Linux may store a
program in many different places, and changing an individual file without
changing the related files may result in files being out of sync and certain
programs becoming damaged.
ps
This command stands for "process status" and checks what processes are
running. Using it is just as easy as typing any other command with options.
The ps command allows the user to view the status of processes currently
running. To use this command, type ps into the terminal. You should get a
printout that looks something like this:
Let's go over each part we see on the chart individually. To the far left, you see
the letters PID, which stands for "process ID." Next to it, are the letters TTY,
which stands for "terminal type." Next to TTY is the TIME followed by CMD,
which represents the commands that are running. Every program that executes
has a process ID so in this case, we have 2 programs running.
Unfortunately, this isn't very useful. As you can see in the table above, this ps
command is only showing us information about 1) itself and 2) the shell terminal
that's open. This is okay if all we're doing is playing with the terminal and trying
to learn the commands but we may need to add more options before this
command becomes useful.
top
This is like the "task manager" command in Windows. It shows you the
programs and processes. Type top in the terminal to use it. To get a list of
commands you can use with top, type top and a list of commands should show
up. It even allows you to kill processes on the top screen by pressing k.
The top command is used to show Linux processes. You can also combine it
with other commands to put it to different uses. For example, you can see active
processes for only user processes, and you can also type in Shift+P to sort
processes according to their CPU usage. This makes it much easier to spot the
processes that gobble up memory and find and kill stubborn, hung up processes.
You can also set the top command to close after refreshing itself a certain
number of times by using the -n option.
sleep
This command allows you to pause the system or an individual script by creating
a dummy process for it to work on. This can come in handy when you're
programming or testing the system for weaknesses. To use this command, type
sleep and the amount of time you want the system to pause into the terminal,
followed by s, m, h, or d for seconds, minutes, hours, or days, respectively.
If you need to pause the system by initiating the sleep command, it's a good idea
to not have the sleep command run for more than one full day. Very few tasks
would require you to put the system on hold for longer.
Options:
Like other commands we've explored, the sleep command can be given with
other commands, or even used as part of a mini-program with the use of the
while loop or other bits of Bash programming. Once you've mastered the basics,
you may think of all sorts of uses for it, depending on what you use Linux shell
scripting for.
Exercise:
Use the echo command with the sleep command. Type "time (echo "string";
sleep <time>; echo "string") and set the time for only a few seconds. Record the
results in your notebook.
jobs
In Linux, a job refers to a group of processes. Rather than having to enter
commands for each individual process, you can, instead, enter commands that
affect the full job, saving you time and making the process more efficient.
Use the jobs command to display the status of jobs started in the terminal
window. For each session, jobs are numbered starting from the number one.
Instead of using PIDs, some programs use job numbers; the foreground and
background commands are examples of this.
Suspend a Job
To pause a job, type Ctrl + z. Notice the ^Z in the output below - that is the Ctrl
+ z.
Exercise:
Go and download a practice file, then kill the job in three different ways. Record
your findings in your notebook. Refer to the previous paragraphs if you need to
refresh yourself on the kill command.
Explanation:
Chapter Summary
In this chapter, we covered how the Linux security system works, the
rights of the root user as compared to other users, how to change
permissions of files, how to view the jobs and processes, and how to
kill jobs.
Linux Installation
4. What is the difference between the root folder and the root user?
5. Is there any danger when storing files in the root directory in Linux?
6. What does the lib library file contain?
7. Is capitalization important in Linux syntax?
Linux Shells
Manipulating Files
19. How would you move a file from one directory to another?
20. How would you copy a file?
21. If you don't want a file on your system anymore, which command
would you use to remove it?
22. How would you remove an empty directory?
23. How would you remove a full directory?
24. Name some ways to view the contents of files.
25. How would you create a blank file?
26. What does the cat command do?
27. Which command would I use if I wanted to print text to the screen?
28. How is the less command different from the more command?
29. If I wanted to view the last five entries of a list, which command
could I use?
30. If I wanted to view the first five entries, which command could I use?
31. Which command could I use if I wanted a list of all files with a
certain title?
32. Which command could I use if I wanted to search for a file with a
certain title?
33. The command grep stands for what? What is grep used for?
34. Which command could I use if I wanted to know how many words,
lines, and bytes a document contains?
Other Commands
Help Commands
42. What are some advantages to using the man command over the --help
option?
46. What does rwx stand for? Why is having permissions for files and
users important?
50. What's the difference between a process and a job? Give an example
of each.
51. What are some potential advantages of the sleep command?
52. How do you put a process that is already running into the
background?
53. How do you tell a process to go to the background at the time you run
it?
54. How do you kill a process?
Passwords
63. What does the chage command do? How is it different from the
passwd command?
64. What's an easy way to set a date of expiration for a password?
Groups
65. How would you add a group? How would you remove a group?
Now, tally up your score. Round to the nearest tenth if needed. How did you do?
If you got 100% of these questions correct, great job! You might know the basics
of the Linux command line now, and you might be ready to take on more
complex and advanced projects.
Project Ideas
Now that you have a general idea of the Linux file system and how it is
structured, along with how to use its basic commands and options, you may want
to further your learning by attempting some basic projects.
Basic-Beginner Friendly
Continue Bash
You might want to continue learning the Bash scripting language and try your
hand at writing more complex commands. You may even try creating a labor-
saving program or two. Such a project will likely require commands like alias
and grep, combined with techniques like piping. After getting familiar with
stringing basic commands together, you can start to use conditional checks and
loops to really power up your scripts.
Let's pretend you want to write a program to find the text files in the current
directory and limit the result to 2 files.
C and C++
To use other Linux features, you might want to learn some basics of the C
programming language. Doing so will enable you to enter commands into the
csh shell, as mentioned before. You may also learn how to write programs and
apps for the Linux OS.
Intermediate
Set Up a Small Home Server
You don't have to wait until you learn a full coding language to do something
productive in Linux. If you have a small computer that you aren't using and want
to re-purpose, you could set up a home server for added security on your own
network.
Before we get started, here are some of the commands that you might need to
know:
mkdir
sudo apt-get install
adduser
addgroup
hostname -i
chmod
Remember that sudo can be read to mean "super user do," and it may be a way
of getting permission to perform administrative tasks that Linux would otherwise
block you from doing. Try entering all of the commands separately rather than
all at once.
tasksel
Explanation:
This command stands for "task select" and is intended for those who want to use
Ubuntu Linux for servers. If you know exactly what you want your server to do,
you can just run the tasksel command to install the software you need to create a
Advanced
The Internet of Things , or IoT, is fascinating. You can connect drones,
wireless "smart" cameras, and even create small robotic appliances that send
messages to a server to let you know their status. You could use IoT technology
for many things, including vending machines that can sense when their inventory
is low and can signal you to order more, eliminating the need for you to check
them by hand. A popular use for this technology is the smart camera.
You can try making your own, small IoT project, like remotely connecting a
Linux terminal to program a headless system to power a robot or remote-
controlled camera. You might need to know Python and have a good idea of how
to connect wirelessly to a Linux machine, as you probably don't want your new
machine to have to receive commands via a terminal you have to access through
a screen on the machine itself.
For this project, you might need to know how to:
Program in Python.
Understand basic robotics principles.
Connect to a Linux system headlessly and wirelessly.
For more information on this, look up some drone and small robot builds. You
may need special cables and some programming knowledge to get your creations
to do what you want. Unfortunately, this book won't be covering much about
programming languages outside of what you may need to know for basic Bash
scripting. If you believe you're ready to tackle a larger project, don't let any of
this discourage you--there are plenty of free resources on the web about getting
started with the exciting world of AI. You may even find communities that will
help you with your builds and projects, even providing step-by-step tutorials.
There are various places to post questions for community feedback too, so you
should definitely try it out if this interests you.
Closing Thoughts
I hope you've enjoyed this book, appreciate Linux a little more, and find the
Linux command line less intimidating. If this book has helped you, consider
leaving a five-star rating on Amazon and Goodreads, and don't forget to share
this book with a friend who wants to learn Linux too.