Linux
Linux
Linux
4.1 Introduction
This is Lab 4: Command Line Basics. By performing this lab, students will learn how to use basic
features of the shell.
In this lab, you will perform the following tasks:
Previous
Next
sysadmin@localhost:~$
Remember: You may need to press Enter in the window to display the prompt.
The prompt tells you that you are user sysadmin; the host or computer you are
using: localhost; and the directory where you are at: ~, which represents your home directory.
When you type a command it will appear at the text cursor. You can use keys such as
the home, end, backspace, and arrowkeys for editing the command you are typing.
Once you have typed the command correctly, press Enter to execute it.
Previous
Next
4.2.1 Step 1
The following command will display the same information that you see in the first part of the
prompt. Make sure that you have selected (clicked on) the Terminal window first and then type
the following command followed by the Enter key:
whoami
sysadmin@localhost:~$ whoami
sysadmin
sysadmin@localhost:~$
The output of the whoami command, sysadmin, displays the user name of the current user.
Although in this case your username is displayed in the prompt, this command could be used to
obtain this information in a situation when the prompt did not contain this information.
Previous
Next
4.2.2 Step 2
The next command displays information about the current system. To be able to see the name of
the kernel you are using, type the following command into the terminal:
uname
sysadmin@localhost:~$ uname
Linux
Many commands that are executed produce text output like this. You can change what output is
produced by a command by using options after the name of the command.
Options for a command can be specified in several ways. Traditionally in UNIX, options were
expressed by a hyphen followed by another character, for example: -n.
In Linux, options can sometimes also be given by two hyphen characters followed by a word, or
hyphenated word, for example: --nodename.
Execute the uname command again twice in the terminal, once with the option -n and again with
the option --nodename. This will display the network node hostname, also found in the prompt.
uname -n
uname --nodename
sysadmin@localhost:~$ uname -n
localhost
sysadmin@localhost:~$ uname --nodename
localhost
Previous
Next
4.2.3 Step 3
The pwd command is used to display your current "location" or current "working" directory. Type
the following command to display the working directory:
pwd
sysadmin@localhost:~$ pwd
/home/sysadmin
sysadmin@localhost:~$
The current directory in the example above is /home/sysadmin. This is also referred to as
your home directory, a special place where you have control of files and other users normally
have no access. By default, this directory is named the same as your username and is located
underneath the /home directory.
As you can see from the output of the command, /home/sysadmin, Linux uses the forward
slash / to separate directories to make what is called a path. The initial forward slash represents
the top level directory, known as the root directory. More information regarding files, directories
and paths will be presented in later labs.
The tilde ~ character that you see in your prompt is also indicating what the current directory is.
This character is a "shortcut" way to represent your home.
Consider This: pwd stands for "print working directory". While it doesn't actually "print" in modern
versions, older UNIX machines didn't have monitors and output of commands went to a printer,
hence the funny name of pwd.
Previous
Next
Previous
Next
4.3.1 Step 1
The echo command can be used to print text, the value of a variable and show how the shell
environment expands metacharacters (more on metacharacters later in this lab). Type the
following command to have it output literal text:
Previous
Next
4.3.2 Step 2
Type the following command to display the value of the PATH variable:
echo $PATH
The PATH variable is displayed by placing a $ character in front of the name of the variable.
This variable is used to find the location of commands. Each of the directories listed above are
searched when you run a command. For example, if you try to run the date command, the shell
will first look for the command in the /home/sysadmin/bin directory and then in
the /usr/local/sbin directory and so on. Once the date command is found, the shell "runs
it”.
Previous
Next
4.3.3 Step 3
Use the which command to determine if there is an executable file named date that is located in
a directory listed in the PATH value:
which date
The output of the which command tells you that when you execute the date command, the
system will run the command /bin/date. The which command makes use of the PATH variable
to determine the location of the date command.
Previous
Next
4.4 Globbing
The use of glob characters in Linux is similar to what many operating systems refer to as
"wildcard" characters. Using glob characters, you match filenames using patterns.
Glob characters are a shell feature, not something that is particular to any specific command. As
a result, you can use glob characters with any Linux command.
When glob characters are used, the shell will "expand" the entire pattern to match all files in the
specified directory that matches the pattern.
For demonstration purposes, we will use the echo command to display this expansion process.
Previous
Next
4.4.1 Step 1
Use the following echo command to display all filenames in the current directory that matches the
glob pattern *:
echo *
sysadmin@localhost:~$ echo *
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$
The asterisk * matches "zero or more" characters in a file name. In the example above, this
results in matching all filenames in the current directory.
The echo command, in turn, displays the filenames that were matched.
Previous
Next
4.4.2 Step 2
The following commands will display all the files in the current directory that start with the letter D,
and the letter P:
echo D*
echo P*
sysadmin@localhost:~$ echo D*
Desktop Documents Downloads
sysadmin@localhost:~$ echo P*
Pictures Public
sysadmin@localhost:~$
Think of the first example, D*, as "match all filenames in the current directory that begin with a
capital d character and have zero or more of any other character after the D".
Previous
Next
4.4.3 Step 3
The asterisk * can be used anywhere in the string. The following command will display all the
files in your current directory that end in the letter s:
echo *s
sysadmin@localhost:~$ echo *s
Documents Downloads Pictures Templates Videos
sysadmin@localhost:~$
Previous
Next
4.4.4 Step 4
Notice that the asterisk can also appear multiple times or in the middle of several characters:
echo D*n*s
Your output should be similar to the following:
The next glob metacharacter that we will examine is the question mark ?. The question mark
matches exactly one character. This single character can be any possible character.
Like the asterisk it can be used anywhere in a string and can appear multiple times.
Previous
Next
4.4.5 Step 5
Since each question mark matches one unknown character, typing six of them will match six
character filenames. Type the following to display the filenames that are exactly six characters
long:
echo ??????
Important: Each ? character must match exactly one character in a filename, no more and no
less than one character.
Previous
Next
4.4.6 Step 6
Using the question mark with other characters will limit the matches. Type the following to display
the file names that start with the letter D and are exactly nine characters long:
echo D????????
Next
4.4.7 Step 7
Wildcards or glob characters can be combined together. The following command will display file
names that are at least six characters long and end in the letter s.
echo ?????*s
Think of the pattern ?????*s to mean "match filenames that begin with any five characters, then
have zero or more of any characters and then end with an s character".
Previous
Next
4.4.8 Step 8
The next glob is similar to the question mark glob to specify one character.
This glob uses a pair of square brackets [ ] to specify which one character will be allowed. The
allowed characters can be specified as a range, a list, or by what is known as a character class.
The allowed characters can also be negated with an exclamation point !.
In the first example, the first character of the file name can be either a D or a P. In the second
example, the first character can be any character except a D or P:
echo [DP]*
echo [!DP]*
Previous
Next
4.4.9 Step 9
In these next examples, a range of characters will be specified. In the first example, the first
character of the file name can be any character starting at D and ending at P. In the second
example, this range of characters is negated, meaning any single character will match as long as
it is not between the letters D and P:
echo [D-P]*
echo [!D-P]*
You may be asking yourself "who decides what letters come between D and P ?". In this case the
answer is fairly obvious (E, F, G, H, I, J, K, L, M, N and O), but what if the range was [1-A]?
The ASCII text table is used to determine the range of characters. You can view this table by
searching for it on the Internet or typing the following command: ascii
So, what characters does the glob [1-A] match? According to the ASCII text
table: 1, 2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, @ and A.
Previous
Next
4.5 Quoting
There are three types of quotes used by the Bash shell: single quotes ('), double quotes (") and
back quotes (`). These quotes have special features in the Bash shell as described below.
To understand single and double quotes, consider that there are times that you don't want the
shell to treat some characters as "special". For example, as you learned earlier in this lab,
the * character is used as a wildcard. What if you wanted the *character to just mean an
asterisk?
Single quotes prevent the shell from "interpreting" or expanding all special characters. Often
single quotes are used to protect a string from being changed by the shell, so that the string can
be interpreted by a command as a parameter to affect the way the command is executed.
Double quotes stop the expansion of glob characters like the asterisk (*), question mark (?), and
square brackets ( [ ] ). Double quotes do allow for both variable expansion and command
substitution (see back quotes) to take place.
Back quotes cause "command substitution" which allows for a command to be executed within
the line of another command.
When using quotes, they must be entered in pairs or else the shell will not consider the command
complete.
While single quotes are useful for blocking the shell from interpreting one or more characters, the
shell also provides a way to block the interpretation of just a single character called "escaping"
the character. To "escape" the special meaning of a shell metacharacter, the
backslash \ character is used as a prefix to that one character.
Previous
Next
4.5.1 Step 1
Execute the following command to use back quotes ` to execute the date command within the
line of the echo command:
Previous
Next
4.5.2 Step 2
You can also place $( before the command and ) after the command to accomplish command
substitution:
Why two different methods that accomplish the same thing? Backquotes look very similar to
single quotes, making it harder to "see" what a command is supposed to do. Originally shells
used backquotes; the $(command) format was added in a later version of the Bash shell to make
the statement more visually clear.
Previous
Next
4.5.3 Step 3
If you don't want the backquotes to be used to execute a command, place single quotes around
them. Execute the following:
Previous
Next
4.5.4 Step 4
Note that you could also place a backslash character in front of each backquote character.
Execute the following:
Previous
Next
4.5.5 Step 5
Double quote characters don't have any effect on backquote characters. The shell will still use
them as command substitution. Execute the following to see a demonstration:
Previous
Next
4.5.6 Step 6
Double quote characters will have an effect on wildcard characters, disabling their special
meaning. Execute the following:
echo D*
echo "D*"
sysadmin@localhost:~$ echo D*
Desktop Documents Downloads
sysadmin@localhost:~$ echo "D*"
D*
sysadmin@localhost:~$
Important:
Quoting may seem trivial and weird at the moment, but as you gain more experience working in
the command shell, you will discover that having a good understanding of how different quotes
work is critical to using the shell.
Previous
Next
Previous
Next
4.6.1 Step 1
Execute the following three commands together separated by semicolons:
As you can see the output shows all three commands executed sequentially:
Previous
Next
4.6.2 Step 2
Now, put three commands together separated by semicolons, where the first command executes
with a failure result:
Note that in the previous example, all three commands still executed even though the first one
failed. While you can't see from the output of the false command, it did execute. However, when
commands are separated by the ; character, they are completely independent of each other.
Previous
Next
4.6.3 Step 3
Next, use "logical and" to separate the commands:
Because each echo statement executes correctly, a return value of success is provided, allowing
the next statement to also be executed.
Previous
Next
4.6.4 Step 4
Use "logical and" with a command that fails as shown below:
The first echo command succeeds and we see its output. The false command executes with a
failure result, so the last echostatement is not executed.
Previous
Next
4.6.5 Step 5
The "or" characters separating the following commands demonstrates how the failure before the
"or" statement causes the command after it to execute; however, a successful first statement
causes the command to not execute:
Previous
Next
Previous
Next
4.7.1 Step 1
Execute a few commands and then execute the history command:
date
clear
echo Hi
history
Remember: The date command will print the time and date on the system. The clear command
clears the screen.
Your output should be similar to the following:
sysadmin@localhost:~$ echo Hi
Hi
sysadmin@localhost:~$ history
1 date
2 clear
3 echo Hi
4 history
sysadmin@localhost:~$
Your command numbers will likely differ from those provided above. This is because you likely
have executed a different number of commands.
Previous
Next
4.7.2 Step 2
To view a limited number of commands, the history command can take a number as a
parameter to display exactly that many recent entries. Type the following command to display the
last five commands from your history:
history 5
sysadmin@localhost:~$ history 5
185 false || Fail Or
186 false || echo Fail Or
187 true || echo Nothing to see here
188 history
189 history 5
sysadmin@localhost:~$
Previous
Next
4.7.3 Step 3
To execute a command again, type the exclamation point and the history list number. For
example, to execute the 94th command in your history list, you would execute the following:
!94
Previous
Next
4.7.4 Step 4
Next, experiment with accessing your history using the up arrow keys and down arrow keys.
Keep pressing the up arrow keyuntil you find a command you want to execute. If necessary use
other keys to edit the command and then press Enter to execute the command.
Previous
Next
5.1 Introduction
This is Lab 5: Getting Help. By performing this lab, students will learn how to get help on
commands and find files.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
5.2.1 Step 1
Execute commands in the bash shell by typing the command and then pressing the Enter key.
For example, type the following command to display today's date:
date
sysadmin@localhost:~$ date
Tue Jan 19 17:27:20 UTC 2016
sysadmin@localhost:~$
Previous
Next
5.2.2 Step 2
To learn more about commands, access the manual page for the command with
the man command. For example, execute the following command to learn more about
the date command:
man date
sysadmin@localhost:~$ man date
NAME
date - print or set the system date and time
SYNOPSIS
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
DESCRIPTION
Display the current time in the given FORMAT, or set the system date
.
-d, --date=STRING
display time described by STRING, not `now'
-f, --file=DATEFILE
like --date once for each line of DATEFILE
-r, --reference=FILE
display the last modification time of FILE
-R, --rfc-2822
output date and time in RFC 2822 format. Example: Mon, 07
Aug
Manual page date(1) line 1 (press h for help or q to quit)
Note: Documents that are displayed with the man command are called "Man Pages".
If the man command can find the manual page for the argument provided, then that manual page
will be displayed using a command called less. The following table describes useful keys that
can be used with the less command to control the output of the display:
Key Purpose
Next
5.2.3 Step 3
Type the letter h to see a list of movement commands. After reading the movement commands,
type the letter q to get back to the document.
MOVING
Note that the man pages might be a bit of a mystery to you now, but as you learn more about
Linux, you will find they are a very valuable resource.
Previous
Next
5.2.4 Step 4
Searches are not case sensitive and do not "wrap" around from the bottom to top, or vice versa.
Start a forward search for the word "file" by typing:
/file
Note that what you are typing will appear at the bottom left portion of the screen.
-r, --reference=FILE
display the last modification time of FILE
-R, --rfc-2822
output date and time in RFC 2822 format. Example: Mon, 07
Aug
/file
Previous
Next
5.2.5 Step 5
Notice that the text matching the search is highlighted. You can move forward to the next match
by pressing n. Also try moving backwards through the matches by pressing N:
-f, --file=DATEFILE
like --date once for each line of DATEFILE
-r, --reference=FILE
display the last modification time of FILE
-R, --rfc-2822
output date and time in RFC 2822 format. Example: Mon, 07
Aug
2006 12:34:56 -0600
--rfc-3339=TIMESPEC
output date and time in RFC 3339 format. TIMESPEC=`date', `s
ec-
onds', or `ns' for date and time to the indicated precisi
on.
Date and time components are separated by a single spa
ce:
2006-08-07 12:34:56-06:00
-s, --set=STRING
set time described by STRING
Previous
Next
5.2.6 Step 6
Use the movement commands previously described (such as using the spacebar to move down
one screen) to read the man page for the date command. When you are finished reading,
type q to exit the man page.
Previous
Next
5.2.7 Step 7
In some cases you may not remember the exact name of the command. In these cases you can
use the -k option to the mancommand and provide a keyword argument. For example, execute
the following command to display a summary of all man pages that have the keyword "password"
in the description:
man -k password
sysadmin@localhost:~$ man -k password
chage (1) - change user password expiry information
chgpasswd (8) - update group passwords in batch mode
chpasswd (8) - update passwords in batch mode
cpgr (8) - copy with locking the given file to the password or
gr...
cppw (8) - copy with locking the given file to the password or
gr...
expiry (1) - check and enforce password expiration policy
login.defs (5) - shadow password suite configuration
pam_pwhistory (8) - PAM module to remember last passwords
pam_unix (8) - Module for traditional password authentication
passwd (1) - change user password
passwd (1ssl) - compute password hashes
passwd (5) - the password file
pwck (8) - verify integrity of password files
pwconv (8) - convert to and from shadow passwords and groups
shadow (5) - shadowed password file
shadowconfig (8) - toggle shadow passwords on and off
unix_chkpwd (8) - Helper binary that verifies the password of the curr
en...
unix_update (8) - Helper binary that updates the password of a given u
ser
vipw (8) - edit the password, group, shadow-password or shadow-
gr...
sysadmin@localhost:~$
The -k option to the man command will often produce a huge amount of output. You will learn a
technique in a later lab to either limit this output or allow you to easily scroll though the data. For
now, just use the scrollbar on the right hand side of the terminal window to move the display up
and down as needed.
Previous
Next
5.2.8 Step 8
Note that the apropos command is another way of viewing man page summaries with a keyword.
Type the following command:
apropos password
sysadmin@localhost:~$ apropos password
chage (1) - change user password expiry information
chgpasswd (8) - update group passwords in batch mode
chpasswd (8) - update passwords in batch mode
cpgr (8) - copy with locking the given file to the password or
gr...
cppw (8) - copy with locking the given file to the password or
gr...
expiry (1) - check and enforce password expiration policy
login.defs (5) - shadow password suite configuration
pam_pwhistory (8) - PAM module to remember last passwords
pam_unix (8) - Module for traditional password authentication
passwd (1) - change user password
passwd (1ssl) - compute password hashes
passwd (5) - the password file
pwck (8) - verify integrity of password files
pwconv (8) - convert to and from shadow passwords and groups
shadow (5) - shadowed password file
shadowconfig (8) - toggle shadow passwords on and off
unix_chkpwd (8) - Helper binary that verifies the password of the curr
en...
unix_update (8) - Helper binary that updates the password of a given u
ser
vipw (8) - edit the password, group, shadow-password or shadow-
gr...
sysadmin@localhost:~$
Previous
Next
5.2.9 Step 9
There are often multiple man pages with the same name. For example, the previous command
showed three pages for passwd. Execute the following command to view the man pages for the
word passwd:
man -f passwd
sysadmin@localhost:~$ man -f passwd
passwd (5) - the password file
passwd (1) - change user password
passwd (1ssl) - compute password hashes
sysadmin@localhost:~$
The fact that there are different man pages for the same "name" is confusing for many beginning
Linux users. Man pages are not just for Linux commands, but also for system files and other
"features" of the Operating System. Additionally, there will sometimes be two commands with the
same name, as in the example provided above.
The different man pages are distinguished by "sections". By default there are nine default
sections of man pages:
When you type a command such as man passwd, the first section is searched and, if a match is
found, the man page is displayed. The man -f passwd command that you previously executed
shows that there is a section 1 man page for passwd: passwd (1). As a result, that is the one
that is displayed by default.
Previous
Next
5.2.10 Step 10
To display a man page for a different section, provide the section number as the first argument to
the man command. For example, execute the following command:
man 5 passwd
PASSWD(5) File Formats and Conversions PASSWD
(5)
NAME
passwd - the password file
DESCRIPTION
/etc/passwd contains one line for each user account, with seven fiel
ds
delimited by colons (":"). These fields are:
o login name
o numerical user ID
o numerical group ID
Previous
Next
5.2.11 Step 11
Instead of using man -f to display all man page sections for a name, you can also use
the whatis command:
whatis passwd
sysadmin@localhost:~$ whatis passwd
passwd (5) - the password file
passwd (1) - change user password
passwd (1ssl) - compute password hashes
sysadmin@localhost:~$
Previous
Next
5.2.12 Step 12
Almost all system features (commands, system files, etc.) have man pages. Some of these
features also have a more advanced feature called info pages. For example, execute the
following command:
info date
File: coreutils.info, Node: date invocation, Next: arch invocation, Up:
Syst\
em context
Synopses:
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [ MMDDhhmm[[CC]YY][.ss] ]
Normally, `date' uses the time zone rules indicated by the `TZ'
environment variable, or the system default rules if `TZ' is not set.
*Note Specifying the Time Zone with `TZ': (libc)TZ Variable.
Many beginning Linux users find info pages to be easier to read. They are often written more
like "lessons" while man pages are written purely as documentation.
Previous
Next
5.2.13 Step 13
While viewing the info page from the previous step, type the letter h to see a list of movement
commands. Note that they are different from the movement commands used in man pages. After
reading the movement commands, type the letter l (lowercase L) to return to viewing the
document.
Previous
Next
5.2.14 Step 14
Use the movement commands to read the info page for the date command. When you are done,
put your cursor anywhere on the line that reads *Examples of date:: and then press
the Enter key. A new document will be displayed that shows examples of date.
Previous
Next
5.2.15 Step 15
Type the l key to return to the previous screen. When you are finished reading, type q to exit the
info page.
Previous
Next
5.2.16 Step 16
Another way of getting help is by using the --help option to a command. Most commands allow
you to pass an argument of --help to view basic command usage:
date --help
sysadmin@localhost:~$ date --help
Usage: date [OPTION]... [+FORMAT]
or: date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Display the current time in the given FORMAT, or set the system date.
Previous
Next
5.2.17 Step 17
Some system features also have more detailed help documents located in
the /usr/share/doc directory structure. Execute the following command to view the contents
of this document:
ls /usr/share/doc
sysadmin@localhost:~$ ls /usr/share/doc
adduser libdrm2 libx11-data
apt libedit2 libxau6
ascii libelf1 libxcb1
base-files libffi6 libxdmcp6
base-passwd libgcc1 libxext6
bash libgcrypt11 libxml2
bind9 libgdbm3 libxmuu1
bind9-host libgeoip1 locales
bind9utils libgettextpo0 login
bsdmainutils libglib2.0-0 logrotate
bsdutils libgnutls26 lsb-base
busybox-initramfs libgomp1 makedev
bzip2 libgpg-error0 man-db
ca-certificates libgpm2 mawk
coreutils libgssapi-krb5-2 mc
cpio libgssapi3-heimdal mc-data
cron libhcrypto4-heimdal mime-support
curl libheimbase1-heimdal mlocate
dash libheimntlm0-heimdal module-init-tools
Note that in almost all cases, the man pages and info pages will provide you with the information
that you need. However, if you need more in-depth information (something that system
administrators sometimes need), then you may find this information in the files located in
the /usr/share/doc directory.
Previous
Next
Next
5.3.1 Step 1
An easy way to search for a file is to use the locate command. For example, you can find the
location of the crontab file by executing the following command:
locate crontab
sysadmin@localhost:~$ locate crontab
/etc/crontab
/usr/bin/crontab
/usr/share/doc/cron/examples/crontab2english.pl
/usr/share/man/man1/crontab.1.gz
/usr/share/man/man5/crontab.5.gz
sysadmin@localhost:~$
Previous
Next
5.3.2 Step 2
Note that the output from the previous example includes files that have crontab as part of their
name. To find files that are just named crontab, use the following command:
locate -b "\crontab"
sysadmin@localhost:~$ locate -b "\crontab"
/etc/crontab
/usr/bin/crontab
sysadmin@localhost:~$
Note: The locate command makes use of a database that is traditionally updated once per day
(normally in the middle of the night). This database contains a list of all files that were on the
system when the database was last updated.
As a result, any files that you created today will not normally be searchable with
the locate command. If you have access to the system as the root user (the system
administrator account), you can manually update this file by running the updatedbcommand.
Regular users can not update the database file.
Another possible solution to searching for "newer" files is to make use of the find command. This
command searches the live filesystem, rather than a static database. The find command isn't
part of the Linux Essentials objectives for this lab, so it is only mentioned here. Execute man
find if you want to explore this command on your own or wait for the lab that explores
the findcommand.
Previous
Next
5.3.3 Step 3
You may just want to find where a command (or its man pages) is located. This can be
accomplished with the whereis command :
whereis passwd
sysadmin@localhost:~$ whereis passwd
passwd: /usr/bin/passwd /etc/passwd /usr/share/man/man1/passwd.1.gz /usr/sh
are/man/man1/passwd.1ssl.gz /usr/share/man/man5/passwd.5.gz
sysadmin@localhost:~$
The whereis command only searches for commands and man pages, not just any file.
Recall from earlier that there is more than one passwd man page on the system. This is why you
see multiple file names and man pages (the files that end in .gz are man pages) when you
execute the previous command.
Previous
Next
6.1 Introduction
This is Lab 6: Listing Files and Directories. By performing this lab, students will learn how to
navigate and manage files and directories.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
6.2.1 Step 1
Type the following command to print the working directory:
pwd
sysadmin@localhost:~$ pwd
/home/sysadmin
sysadmin@localhost:~$
The working directory is the directory that your terminal window is currently "in". This is also
called the current directory. This will be important for when you are running future commands as
they will behave differently based on the directory you are currently in.
The output of the pwd command (/home/sysadmin in the example above) is called the path.
The first slash represents the root directory, the top level of the directory structure.
In the output above, home is a directory under the root directory and sysadmin is a directory
under the home directory.
When you first open a terminal window, you will be placed in your home directory. This is a
directory where you have full access and other users normally have no access by default. To see
the path to your home directory, you can execute the following command to view the value of
the HOME variable:
echo $HOME
sysadmin@localhost:~$ echo $HOME
/home/sysadmin
sysadmin@localhost:~$
Previous
Next
6.2.2 Step 2
You can use the cd command with a path to a directory to change your current directory. Type
the following command to make the root directory your current working directory and verify with
the pwd command:
cd /
pwd
sysadmin@localhost:~$ cd /
sysadmin@localhost:/$ pwd
/
sysadmin@localhost:/$
Previous
Next
6.2.3 Step 3
To change back to your home directory, the cd command can be executed without a path.
Change back to your home directory and verify by typing the following commands:
cd
pwd
sysadmin@localhost:/$ cd
sysadmin@localhost:~$ pwd
/home/sysadmin
sysadmin@localhost:~$
Notice the change in the prompt. The tilde ~ character represents your home directory. This part
of the prompt will tell you what directory you are currently in.
Previous
Next
6.2.4 Step 4
The cd command may be entered with a path to a directory specified as an argument. Execute
the cd command with the /home directory as an argument by typing the following:
cd /home
pwd
sysadmin@localhost:~$ cd /home
sysadmin@localhost:/home$ pwd
/home
sysadmin@localhost:/home$
When the path that is provided as an argument to the cd command starts with the forward
slash /, that path is referred to as an “absolute path”. Absolute paths are always complete paths
from the root directory to a sub-directory or file.
Previous
Next
6.2.5 Step 5
Change back to your home directory, using the cd command with the tilde ~ as an argument:
cd ~
pwd
sysadmin@localhost:/home$ cd ~
sysadmin@localhost:~$ pwd
/home/sysadmin
sysadmin@localhost:~$
When the path that is provided as an argument to cd command starts with a tilde ~ character, the
terminal will expand the character to the home directory of a user with an account on the system.
If either no other characters or a forward slash follows the tilde, then it will expand to the home
directory of the user currently active in the shell.
If a user name immediately follows the tilde character, then the shell will expand the tilde and
user name to the home directory of that user name. For example, ~bob would be expanded
to /home/bob.
Paths that start with a tilde are considered absolute paths because after the shell expands the
tilde path, an absolute path is formed.
Previous
Next
6.2.6 Step 6
Use the echo command below to display some other examples of using the tilde as part of path:
Previous
Next
6.2.7 Step 7
Attempt to change to the home directory of the root user by typing the following command:
cd ~root
sysadmin@localhost:~$ cd ~root
-bash: cd: /root: Permission denied
sysadmin@localhost:~$
Notice the error message; it indicates that the shell attempted to execute cd with /root as an
argument and it failed due to permission being denied. You will learn more about file and
directory permissions in a later lab.
Previous
Next
6.2.8 Step 8
Using an absolute path, change to the /usr/bin directory and display the working directory by
using the following commands:
cd /usr/bin
pwd
sysadmin@localhost:~$ cd /usr/bin
sysadmin@localhost:/usr/bin$ pwd
/usr/bin
sysadmin@localhost:/usr/bin$
Previous
Next
6.2.9 Step 9
Use an absolute path to change the /usr directory and display the working directory by issuing
the following commands:
cd /usr
pwd
sysadmin@localhost:/usr/bin$ cd /usr
sysadmin@localhost:/usr$ pwd
/usr
sysadmin@localhost:/usr$
Previous
Next
6.2.10 Step 10
Use an absolute path the change to the /usr/share/doc directory and display the working
directory by issuing the following commands:
cd /usr/share/doc
pwd
sysadmin@localhost:/usr$ cd /usr/share/doc
sysadmin@localhost:/usr/share/doc$ pwd
/usr/share/doc
sysadmin@localhost:/usr/share/doc$
Previous
Next
6.2.11 Step 11
Using a relative path, change to the /usr/share/doc/bash directory and display the working
directory by issuing the following commands:
cd bash
pwd
sysadmin@localhost:/usr/share/doc$ cd bash
sysadmin@localhost:/usr/share/doc/bash$ pwd
/usr/share/doc/bash
sysadmin@localhost:/usr/share/doc/bash$
Note: If there wasn't a bash directory under the current directory, the previous command would
fail.
Previous
Next
6.2.12 Step 12
Use a relative path to change to the directory above the current directory:
cd ..
pwd
sysadmin@localhost:/usr/share/doc/bash$ cd ..
sysadmin@localhost:/usr/share/doc$ pwd
/usr/share/doc
sysadmin@localhost:/usr/share/doc$
Previous
Next
6.2.13 Step 13
Use a relative path to change up one level from the current directory and then down into
the dict directory:
cd ../dict
pwd
sysadmin@localhost:/usr/share/doc$ cd ../dict
sysadmin@localhost:/usr/share/dict$ pwd
/usr/share/dict
sysadmin@localhost:/usr/share/dict$
Previous
Next
Previous
Next
6.3.1 Step 1
To list the contents of the current directory, use the ls command:
cd
ls
sysadmin@localhost:/usr/share/dict$ cd
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$
In the output of the previous ls command the file names were placed in a light blue color. This is
a feature that many distributions of Linux automatically provide through a feature called
an alias (more on this feature in a later lab).
The color indicates what type the item is. The following table describes some of the more
common colors:
Previous
Next
6.3.2 Step 2
Not all files are displayed by default. There are files, called hidden files, that are not displayed by
default. To display all files, including hidden files, use the -a option to the ls command:
ls -a
sysadmin@localhost:~$ ls -a
. .bashrc .selected_editor Downloads Public
.. .cache Desktop Music Templates
.bash_logout .profile Documents Pictures Videos
sysadmin@localhost:~$
Hidden files begin with a period (a dot character). Typically these files and often directories are
hidden because they are not files you normally want to see.
For example, the .bashrc file shown in the example above contains configuration information for
the bash shell. This is a file that you normally don't need to view on a regular basis.
Two important "dot files" exist in every directory: . (which represents the current directory)
and .. (which represents the directory above the current directory).
Previous
Next
6.3.3 Step 3
By itself, the ls command just provided the names of the files and directories within the specified
(or current) directory. Execute the following command to see how the -l option provides more
information about a file:
ls -l /etc/hosts
sysadmin@localhost:~$ ls -l /etc/hosts
-rw-r--r-- 1 root root 150 Jan 22 15:18 /etc/hosts
sysadmin@localhost:~$
So, what does all of this extra output mean? The following table provides a brief breakdown of
what each part of the output of ls -l means:
- The first character, a - in the previous example, indicates what type of "file" this is. A - character is
while a d character would be for a directory.
rw-r--r-- This represents the permissions of the file. Permissions are discussed in a later lab.
Previous
Next
6.3.4 Step 4
Sometimes you want to see not only the contents of a directory, but also the contents of the
subdirectories. You can use the -Roption to accomplish this:
ls -R /etc/udev
sysadmin@localhost:~$ ls -R /etc/udev
/etc/udev:
rules.d udev.conf
/etc/udev/rules.d:
70-persistent-cd.rules README
sysadmin@localhost:~$
The -R option stands for "recursive". All of the files in the /etc/udev directory will be displayed
as well as all of the files in each subdirectory, in this case the rules.d subdirectory.
Be careful of the -R option. Some directories are very, very large!
Previous
Next
6.3.5 Step 5
You can use file globbing (wildcards) to limit which files or directories you see. For example,
the * character can match "zero or more of any characters" in a filename. Execute the following
command to display only the files that begin with the letter s in the /etc directory:
ls -d /etc/s*
sysadmin@localhost:~$ ls -d /etc/s*
/etc/securetty /etc/sgml /etc/shells /etc/ssl /etc/sysctl.conf
/etc/security /etc/shadow /etc/skel /etc/sudoers /etc/sysctl.d
/etc/services /etc/shadow- /etc/ssh /etc/sudoers.d /etc/systemd
sysadmin@localhost:~$
Note that the -d option prevents files from subdirectories from being displayed. It should always
be used with the ls command when you are using file globbing.
Previous
Next
6.3.6 Step 6
The ? character can be used to match exactly 1 character in a file name. Execute the following
command to display all of the files in the /etc directory that are exactly four characters long:
ls -d /etc/????
sysadmin@localhost:~$ ls -d /etc/????
/etc/bind /etc/init /etc/motd /etc/perl /etc/skel
/etc/dpkg /etc/ldap /etc/mtab /etc/sgml /etc/udev
sysadmin@localhost:~$
Previous
Next
6.3.7 Step 7
By using square brackets [ ] you can specify a single character to match from a set of
characters. Execute the following command to display all of the files in the /etc directory that
begin with the letters a, b, c or d:
ls –d /etc/[abcd]*
sysadmin@localhost:~$ ls -d /etc/[abcd]*
/etc/adduser.conf /etc/blkid.conf /etc/cron.weekly
/etc/adjtime /etc/blkid.tab /etc/crontab
/etc/alternatives /etc/ca-certificates /etc/dbus-1
/etc/apparmor.d /etc/ca-certificates.conf /etc/debconf.conf
/etc/apt /etc/calendar /etc/debian_version
/etc/bash.bashrc /etc/cron.d /etc/default
/etc/bash_completion.d /etc/cron.daily /etc/deluser.conf
/etc/bind /etc/cron.hourly /etc/depmod.d
/etc/bindresvport.blacklist /etc/cron.monthly /etc/dpkg
sysadmin@localhost:~$
Previous
Next
Previous
Next
6.4.1 Step 1
Make a copy of the /etc/hosts file and place it in the current directory. Then list the contents of
the current directory before and after the copy:
ls
cp /etc/hosts hosts
ls
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$ cp /etc/hosts hosts
sysadmin@localhost:~$ ls
Desktop Downloads Pictures Templates hosts
Documents Music Public Videos
sysadmin@localhost:~$
Notice how the second ls command displays a copy of the hosts file.
Previous
Next
6.4.2 Step 2
Next you will remove the file, then copy it again, but have the system tell you what is being done.
This can be achieved using the -v or --verbose option. Enter the following commands:
rm hosts
ls
cp –v /etc/hosts hosts
ls
Note that the rm command is used to delete a file. More information on this command will be
provided later in this lab.
Your output should be similar to the following:
sysadmin@localhost:~$ rm hosts
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$ cp -v /etc/hosts hosts
`/etc/hosts' -> `hosts'
sysadmin@localhost:~$ ls
Desktop Downloads Pictures Templates hosts
Documents Music Public Videos
sysadmin@localhost:~$
Note that the -v switch displays the source and target when the cp command is executed.
Previous
Next
6.4.3 Step 3
Enter the following commands to copy the /etc/hosts file, using the period . character to
indicate the current directory as the target:
rm hosts
ls
cp –v /etc/hosts .
ls
sysadmin@localhost:~$ rm hosts
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$ cp -v /etc/hosts .
`/etc/hosts' -> `hosts'
sysadmin@localhost:~$ ls
Desktop Downloads Pictures Templates hosts
Documents Music Public Videos
sysadmin@localhost:~$
The period . character is a handy way to say "the current directory". It can be used with all Linux
commands, not just the cpcommand.
Previous
Next
6.4.4 Step 4
Enter the following commands to copy from the source directory and preserve file attributes by
using the -p option:
rm hosts
ls
cd /etc
ls -l hosts
cp –p hosts /home/sysadmin
cd
ls –l hosts
sysadmin@localhost:~$ rm hosts
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$ cd /etc
sysadmin@localhost:/etc$ ls -l hosts
-rw-r--r-- 1 root root 150 Jan 22 15:18 hosts
sysadmin@localhost:/etc$ cp -p hosts /home/sysadmin
sysadmin@localhost:/etc$ cd
sysadmin@localhost:~$ ls -l hosts
-rw-r--r-- 1 sysadmin sysadmin 150 Jan 22 15:18 hosts
sysadmin@localhost:~$
Notice that the date and permission modes were preserved. Note that the timestamp in the output
above is the same for both the original and the copy (Jan 22 15:18) in the example provided
above. Your output may vary.
Previous
Next
6.4.5 Step 5
Type the following commands to copy using a different target name:
rm hosts
cp -p /etc/hosts ~
cp hosts newname
ls –l hosts newname
rm hosts newname
sysadmin@localhost:~$ rm hosts
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$ cp -p /etc/hosts ~
sysadmin@localhost:~$ cp hosts newname
sysadmin@localhost:~$ ls -l hosts newname
-rw-r--r-- 1 sysadmin sysadmin 150 Jan 22 15:18 hosts
-rw-r--r-- 1 sysadmin sysadmin 150 Jan 22 16:29 newname
sysadmin@localhost:~$ rm hosts newname
sysadmin@localhost:~$
The first copy with the -p option preserved the original timestamp. Recall that the
tilde ~ represents your home directory (/home/sysadmin).
The second copy specified a different filename (newname) as the target. Because it was issued
without the -p option, the system used the current date and time for the target, thus, it did not
preserve the original timestamp found in the source file /etc/hosts.
Finally, note that you can remove more than one file at a time as shown in the last rm command.
Previous
Next
6.4.6 Step 6
To copy all files in a directory use the -R option. For this task, you will copy
the /etc/udev directory and display the contents of the copied directory:
mkdir Myetc
cp –R /etc/udev Myetc
ls –l Myetc
ls –lR Myetc
sysadmin@localhost:~$ mkdir Myetc
sysadmin@localhost:~$ cp -R /etc/udev Myetc
sysadmin@localhost:~$ ls -l Myetc
total 0
drwxr-xr-x 1 sysadmin sysadmin 32 Jan 22 16:35 udev
sysadmin@localhost:~$ ls -lR Myetc
Myetc:
total 0
drwxr-xr-x 1 sysadmin sysadmin 32 Jan 22 16:35 udev
Myetc/udev:
total 4
drwxr-xr-x 1 sysadmin sysadmin 56 Jan 22 16:35 rules.d
-rw-r--r-- 1 sysadmin sysadmin 218 Jan 22 16:35 udev.conf
Myetc/udev/rules.d:
total 8
-rw-r--r-- 1 sysadmin sysadmin 306 Jan 22 16:35 70-persistent-cd.rules
-rw-r--r-- 1 sysadmin sysadmin 1157 Jan 22 16:35 README
sysadmin@localhost:~$
Previous
Next
6.4.7 Step 7
To remove a directory use the -r option to the rm command:
ls
rm -r Myetc
ls
sysadmin@localhost:~$ ls
Desktop Downloads Myetc Public Videos
Documents Music Pictures Templates
sysadmin@localhost:~$ rm -r Myetc
sysadmin@localhost:~$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos
sysadmin@localhost:~$
Note that the rmdir command can also be used to delete directories, but only if the directory is
empty (if it contains no files).
Also note the -r option. This option removes directories and their contents recursively.
Previous
Next
6.4.8 Step 8
Moving a file is analogous to a "cut and paste". The file is “cut” (removed) from the original
location and “pasted” to the specified destination. Move a file in the local directory by executing
the following commands:
touch premove
ls
mv premove postmove
ls
rm postmove
mv premove postmove This command “cuts” the premove file and “pastes” it to a file called postmove
Previous
Next
7.1 Introduction
This is Lab 7: Archiving and Unarchiving Files. By performing this lab, students will learn how to
work with archive files.
In this lab, you will perform the following tasks:
Previous
Next
a. Large files may be difficult to transfer. Making these files smaller helps make transfer
quicker.
b. Transferring multiple files from one system to another can become tedious when there
are many files. Merging them into a single file for transport makes this process easier.
c. Files can quickly take up a lot of space, especially on smaller removable media like thumb
drives. Archiving reduces this problem.
One potential area of confusion that a beginning Linux user may experience stems from the
following question: why are there so many different archiving commands? The answer is that
these commands have different features (for example, some of them allow you to password
protect the archive file) and compression techniques used.
The most important things to know for now is how these different commands function. Over time
you will learn to pick the correct archive tool for any given situation.
Previous
Next
7.2.1 Step 1
Use the following tar command to create an archive of the /etc/udev directory. Save the
backup in the ~/mybackupsdirectory:
cd
mkdir mybackups
tar –cvf mybackups/udev.tar /etc/udev
ls mybackups
sysadmin@localhost:~$ cd
sysadmin@localhost:~$ mkdir mybackups
sysadmin@localhost:~$ tar -cvf mybackups/udev.tar /etc/udev
tar: Removing leading `/' from member names
/etc/udev/
/etc/udev/rules.d/
/etc/udev/rules.d/70-persistent-cd.rules
/etc/udev/rules.d/README
/etc/udev/udev.conf
sysadmin@localhost:~$ ls mybackups/
udev.tar
sysadmin@localhost:~$
The tar command is used to merge multiple files into a single file. By default it does not
compress the data.
The -c option tells the tar command to create a tar file. The -v option stands for "verbose",
which instructs the tarcommand to demonstrate what it is doing. The -f option is used to specify
the name of the tar file.
FYI: tar stands for Tape ARchive. This command was originally used to create tape backups, but
today it is more commonly used to create archive files.
Important: You are not required to use the .tar extension to the archive file name, however it is
helpful for determining the file type. It is considered "good style" when sending an archive file to
another person.
Previous
Next
7.2.2 Step 2
Display the contents of a tar file (t = list contents, v = verbose, f = filename):
Notice that files were backed up recursively using relative path names. This is important because
when you extract the files, they will be placed in your current directory, not override the current
files.
Previous
Next
7.2.3 Step 3
To create a tar file that is compressed use -z option:
Notice the difference in size; first backup (10 Kbytes) is larger than the second backup (1.2
Kbytes).
The -z option makes use of the gzip utility to perform compression.
Previous
Next
7.2.4 Step 4
Extract the contents of an archive. Data is restored to the current directory by default:
cd mybackups
tar –xvf udev.tar.gz
ls
ls etc
ls etc/udev
ls etc/udev/rules.d
sysadmin@localhost:~$ cd mybackups
sysadmin@localhost:~/mybackups$ ls
udev.tar udev.tar.gz
sysadmin@localhost:~/mybackups$ tar -xvf udev.tar.gz
etc/udev/
etc/udev/rules.d/
etc/udev/rules.d/70-persistent-cd.rules
etc/udev/rules.d/README
etc/udev/udev.conf
sysadmin@localhost:~/mybackups$ ls
etc udev.tar udev.tar.gz
sysadmin@localhost:~/mybackups$ ls etc
udev
sysadmin@localhost:~/mybackups$ ls etc/udev
rules.d udev.conf
sysadmin@localhost:~/mybackups$ ls etc/udev/rules.d
70-persistent-cd.rules README
sysadmin@localhost:~/mybackups$
If you wanted the files to "go back" into their original location, you could first cd to the / directory
and then run the tarcommand. However, in this example, this would require you to be logged in
as an administrator because creating files in the /etc directory can only be done by the
administrator.
Previous
Next
7.2.5 Step 5
To add a file to an existing archive, use the -r option to the tar command. Execute the following
commands to perform this action and verify the existence of the new file in the tar archive:
Previous
Next
7.2.6 Step 6
In the following examples, you will use gzip and gunzip to compress and uncompress a file.
Execute the following commands to compress a copy of the words file:
cp /usr/share/dict/words .
ls -l words
gzip words
ls -l words.gz
sysadmin@localhost:~/mybackups$ cp /usr/share/dict/words .
sysadmin@localhost:~/mybackups$ ls -l words
-rw-r--r-- 1 sysadmin sysadmin 938848 Jan 25 07:39 words
sysadmin@localhost:~/mybackups$ gzip words
sysadmin@localhost:~/mybackups$ ls -l words.gz
-rw-r--r-- 1 sysadmin sysadmin 255996 Jan 25 07:39 words.gz
sysadmin@localhost:~/mybackups$
Notice the size of the zipped file (255996 bytes in the example above) is much smaller than the
original file (938848 bytes in the example above).
Very important: When you use gzip, the original file is replaced by the zipped file. In the
example above, the file words was replaced with words.gz.
When you unzip the file, the zipped file will be replaced with the original file.
Previous
Next
7.2.7 Step 7
Execute the following commands to uncompress the words.gz file:
ls -l words.gz
gunzip words.gz
ls -l words
sysadmin@localhost:~/mybackups$ ls -l words.gz
-rw-r--r-- 1 sysadmin sysadmin 255996 Jan 25 07:39 words.gz
sysadmin@localhost:~/mybackups$ gunzip words.gz
sysadmin@localhost:~/mybackups$ ls -l words
-rw-r--r-- 1 sysadmin sysadmin 938848 Jan 25 07:39 words
sysadmin@localhost:~/mybackups$
Linux provides a large number of compression utilities in addition to gzip/gunzip. Each of them
have pros and cons (faster compression, better compression rates, more flexible, more portable,
faster decompression, etc.).
The gzip/gunzip commands are very popular in Linux, but you should be aware
that bzip2/bunzip2 are also popular on some Linux distributions. It is fortunate that most of the
functionality (the way you run the commands) and options are the same as gzip/gunzip.
Previous
Next
7.2.8 Step 8
Using bzip2 and bunzip2 to compress and uncompress a file is very similar to
using gzip and gunzip. The compressed file is created with a .bz2 extension. The extension is
removed when uncompressed. Execute the following commands to compress a copy of
the words file:
ls -l words
bzip2 words
ls -l words.bz2
sysadmin@localhost:~/mybackups$ ls -l words
-rw-r--r-- 1 sysadmin sysadmin 938848 Jan 25 07:39 words
sysadmin@localhost:~/mybackups$ bzip2 words
sysadmin@localhost:~/mybackups$ ls -l words.bz2
-rw-r--r-- 1 sysadmin sysadmin 335405 Jan 25 07:39 words.bz2
sysadmin@localhost:~/mybackups$
If you compare the resulting .bz2 file size (335405) to the .gz file size (255996) from Step #7,
you will notice that gzipdid a better job compressing this particular file.
Previous
Next
7.2.9 Step 9
Execute the following commands to uncompress the words.bz2 file:
ls -l words.bz2
bunzip2 words.bz2
ls -l words
sysadmin@localhost:~/mybackups$ ls -l words.bz2
-rw-r--r-- 1 sysadmin sysadmin 335405 Jan 25 07:39 words.bz2
sysadmin@localhost:~/mybackups$ bunzip2 words.bz2
sysadmin@localhost:~/mybackups$ ls -l words
-rw-r--r-- 1 sysadmin sysadmin 938848 Jan 25 07:39 words
While gzip and bzip archive files are commonly used in Linux, the zip archive type is more
commonly used by other operating systems, such as Windows. In fact, the Windows Explorer
application has built-in support to extract zip archive files.
Therefore, if you are planning to share an archive with Windows users, it is usually preferred to
use the zip archive type. Unlike gzip and bzip2, when a file is compressed with
the zip command, a copy of the original file is compressed and the original remains
uncompressed.
Previous
Next
7.2.10 Step 10
Use the zip command to compress the words file:
The first argument (words.zip in the example above) of the zip command is the file name that
you wish to create. The remaining arguments (words in the example above) are the files that you
want placed in the compressed file.
Important: You are not required to use the .zip extension to the compressed file name;
however, it is helpful for determining the file type. It is also considered "good style" when sending
an archive file to another person.
Previous
Next
7.2.11 Step 11
Compress the /etc/udev directory and its contents with zip compression:
The tar command discussed earlier in this lab automatically descends through any
subdirectories of a directory specified to be archived. With the bzip2, gzip, and zip commands
the -r option must be specified in order to perform recursion into subdirectories.
Previous
Next
7.2.12 Step 12
To view the contents of a zip archive, use with the -l option with the unzip command:
unzip -l udev.zip
Next
7.2.13 Step 13
To extract the zip archive, use the unzip command without any options. In this example we first
need to delete the files that were created in the earlier tar example:
rm -r etc
unzip udev.zip
sysadmin@localhost:~/mybackups$ rm -r etc
sysadmin@localhost:~/mybackups$ unzip udev.zip
Archive: udev.zip
creating: etc/udev/
creating: etc/udev/rules.d/
inflating: etc/udev/rules.d/70-persistent-cd.rules
inflating: etc/udev/rules.d/README
inflating: etc/udev/udev.conf
sysadmin@localhost:~/mybackups$
Previous
Next
8.1 Introduction
This is Lab 8: Pipes, Redirection and REGEX. By performing this lab, students will learn how to
redirect text streams, use regular expressions, and commands for filtering text files.
In this lab, you will perform the following tasks:
1. Learn how to redirect and pipe standard input, output and error channels.
2. Use regular expressions to filter output of commands or file content.
3. View large files or command output with programs for paging, and viewing selected
portions.
Previous
Next
8.2.1 Step 1
Use the redirection symbol > to redirect the output from the normal output of stdout (terminal) to
a file. Type the following:
Previous
Next
8.2.2 Step 2
When you use the > symbol to redirect stdout, the contents of the file are first destroyed. Type
the following commands to see a demonstration:
cat mymessage
echo Greetings > mymessage
cat mymessage
Notice that using one redirection symbol overwrites an existing file. This is called "clobbering" a
file.
Previous
Next
8.2.3 Step 3
You can avoid clobbering a file by using >> instead of >. By using >> you append to a file.
Execute the following commands to see a demonstration of this:
cat mymessage
echo "How are you?" >> mymessage
cat mymessage
Notice that by using >> all existing data is preserved and the new data is appended at the end of
the file.
Previous
Next
8.2.4 Step 4
The find command is a good command to demonstrate how stderr works. This command
searches the filesystem for files based on criteria such as filename. Run the following command
and observe the output:
Notice the error message indicating you do not have permission to access certain
files/directories. This is because as a regular user, you don't have right to "look inside" some
directories. These types of error messages are sent to stderr, not stdout.
The find command will be covered in greater detail later. The command is just being used now
to demonstrate the difference between stdout and stderr.
Previous
Next
8.2.5 Step 5
To redirect stderr (error messages) to a file issue the following command:
Recall that the file descriptor for stderr is the number 2, so it is used along with the > symbol to
redirect the sdterroutput to a file called err.txt. Note that 1> is the same as >.
Note: The previous example demonstrates why knowing redirection is important. If you want to
"ignore" the errors that the find command displays, you can redirect those messages into a file
and look at them later, making it easier to focus on the rest of the output of the command.
Previous
Next
8.2.6 Step 6
You can also redirect stdout and stderr into two separate files.
Notice that a space is permitted but not required after the > redirection symbol.
Previous
Next
8.2.7 Step 7
To redirect both standard output (stdout) and standard error (stderr) to one file, first
redirect stdout to a file and then redirect stderr to that same file by using the notation 2>&1.
The 2>&1 part of the command means send the stderr (channel 2) to the same place
where stdout (channel 1) is going.
Previous
Next
8.2.8 Step 8
Standard input (stdin) can also be redirected. Normally stdin comes from the keyboard, but
sometimes you want it to come from a file instead. For example, the tr command translates
characters, but it only accepts data from stdin, never from a filename given as an argument.
This is great when you want to do something like capitalize data that is inputted from the
keyboard (Note: Press Control+d, to signal the tr command to stop processing standard input):
tr a-z A-Z
this is interesting
how do I stop this?
^D
Previous
Next
8.2.9 Step 9
The tr command accepts keyboard input (stdin), translates the characters and then sends the
output to stdout. To create a file of all lower case characters, execute the following:
Press the Enter key to make sure your cursor is on the line below "This works!", then
use Control+d to stop input. To verify you created the file, execute the following command:
cat myfile
Previous
Next
8.2.10 Step 10
Execute the following commands to use the tr command by redirecting stdin from a file:
cat myfile
tr a-z A-Z < myfile
Previous
Next
8.2.11 Step 11
Another popular form of redirection is to take the output of one command and send it into another
command as input. For example, the output of some commands can be massive, resulting in the
output scrolling off the screen too quickly to read. Execute the following command to take the
output of the ls command and send it into the more command which displays one page of data at
a time:
ls -l /etc | more
You will need to press the spacebar to continue or you can also press CTRL+c to escape this
listing.
The cut command is useful for extracting fields from files that are either delimited by a character,
like the colon (:) in /etc/passwd, or that have a fixed width. It will be used in the next few
examples as it typically provides a great deal of output that we can use to demonstrate using
the | character.
Previous
Next
8.2.12 Step 12
In the following example, you will use a command called cut to extract all of the usernames from
a database called /etc/passwd (a file that contains user account information). First, try running
the command cut by itself:
Previous
Next
8.2.13 Step 13
The output in the previous example was unordered and scrolled off the screen. In the next step
you are going to take the output of the cut command and send it into the sort command to
provide some order to the output:
Previous
Next
8.2.14 Step 14
Now the output is sorted, but it still scrolls off the screen. Send the output of the sort command
to the more command to solve this problem:
Previous
Next
The command will begin the search in the directory specified and recursively search all of the
subdirectories.
Previous
Next
8.3.1 Step 1
Search for files beginning in your home directory containing the name bash.
Previous
Next
8.3.2 Step 2
Find files that were modified (or created) less than 5 minutes ago in the specified directory by
using the following commands:
The first find command does not find files that were modified within the time specified. You then
created a file by using the touch command and ran the find command again, resulting in
the find command discovering the new file.
The Music directory was displayed with the second find command because the directory was
modified, the result of a file being added to the directory.
Previous
Next
8.3.2 Step 2
Find files that were modified (or created) less than 5 minutes ago in the specified directory by
using the following commands:
The first find command does not find files that were modified within the time specified. You then
created a file by using the touch command and ran the find command again, resulting in
the find command discovering the new file.
The Music directory was displayed with the second find command because the directory was
modified, the result of a file being added to the directory.
Previous
Next
8.3.4 Step 4
Find files of type “directory” in the specified location.
Previous
Next
8.3.5 Step 5
To verify that the output displays directories, use the -ls option. The find command uses the -
print option by default which displays just file names. The -ls option provides file details:
Recall that the d character before the permissions rwxr-x-r-x indicates that the file is actually
a directory.
Previous
Next
Previous
Next
8.4.1 Step 1
The /etc/passwd is likely too large to be displayed on the screen without scrolling the screen.
To see a demonstration of this, use the cat command to display the entire contents of
the /etc/passwd file:
cat /etc/passwd
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
bind:x:102:105::/var/cache/bind:/bin/false
sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin
operator:x:1000:37::/root:/bin/sh
sysadmin:x:1001:1001:System Administrator,,,,:/home/sysadmin:/bin/bash
sysadmin@localhost:~$
Previous
Next
8.4.2 Step 2
Use the more command to display the entire contents of the /etc/passwd file:
more /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
bind:x:102:105::/var/cache/bind:/bin/false
sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin
operator:x:1000:37::/root:/bin/sh
--More--(92%)
Note: The --More--(92%) indicates you are "in" the more command and 92% through the
current data.
Previous
Next
8.4.3 Step 3
While you are in the more command, you can view the help screen by pressing the h key:
Previous
Next
8.4.4 Step 4
Press the Spacebar to view the rest of the document:
<SPACE>
In the next example, you will learn how to search a document using either
the more or less commands.
Searching for a pattern within both the more and less commands is done by typing the slash, /,
followed by the pattern to find. If a match is found, the screen should scroll to the first match. To
move forward to the next match, press the n key. With the less command you can also move
backwards to previous matches by pressing the N (capital n) key.
Previous
Next
8.4.5 Step 5
Use the less command to display the entire contents of the /etc/passwd file. Then search for
the word bin, use n to move forward, and N to move backwards. Finally, quit the less pager by
typing the letter q:
less /etc/passwd
/bin
nnnNNNq
Important: Unlike the more command which automatically exits when you reach the end of a file,
you must press a quit key such as q to quit the less program.
Previous
Next
8.4.6 Step 6
You can use the head command to display the top part of a file. By default, the head command
will display the first ten lines of the file:
head /etc/passwd
Previous
Next
8.4.7 Step 7
Use the tail command to display the last ten lines of the /etc/passwd file:
tail /etc/passwd
Previous
Next
8.4.8 Step 8
Use the head command to display the first two lines of the /etc/passwd file:
head -2 /etc/passwd
Previous
Next
8.4.9 Step 9
Execute the following command line to pipe the output of the ls command to the tail command,
displaying the last five file names in the /etc directory:
ls /etc | tail -5
As you've seen, both head and tail commands output ten lines by default. You could also use
an option -# (or you can use the option -n #, where # is a number of lines to output). Both
commands can be used to read standard input from a pipe that receives output from a command.
You have also seen where head and tail commands are different: the head command starts
counting its lines to output from the top of the data, whereas the tail command counts the
number of lines to output from the bottom of the data. There are some additional differences
between these two commands as demonstrated in the next few tasks.
Previous
Next
8.4.10 Step 10
Another way to specify how many lines to output with the head command is to use the option -n
-#, where # is number of lines counted from the bottom of the output to exclude. Notice the minus
symbol - in front of the #. For example, if the /etc/passwd contains 24 lines and the following
command will display lines 1-4, excluding the last twenty lines:
Previous
Next
Previous
Next
8.5.1 Step 1
The use of grep in its simplest form is to search for a given string of characters, such as sshd in
the /etc/passwd file. The grep command will print the entire line containing the match:
cd /etc
grep sshd passwd
sysadmin@localhost:~$ cd /etc
sysadmin@localhost:/etc$ grep sshd passwd
sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin
sysadmin@localhost:/etc$
Previous
Next
8.5.2 Step 2
Regular expressions are "greedy" in the sense that they will match every single instance of the
specified pattern:
Note the red highlights indicate what exactly was matched. You can also see that all occurrences
of root were matched on each line.
Previous
Next
8.5.3 Step 3
To limit the output, you can use regular expressions to specify a more precise pattern. For
example, the caret ( ^ ) character can be used to match a pattern at the beginning of a line; so
when you execute the following command line, only lines that begin with root should be
matched and displayed:
Note that there are two additional instances of the word root but only the one appearing at the
beginning of the line is matched (displayed in red).
Best Practice: Use single quotes (not double quotes) around regular expressions to prevent the
shell program from trying to interpret them.
Previous
Next
8.5.4 Step 4
Match the pattern sync anywhere on a line:
Previous
Next
8.5.5 Step 5
Use the $ symbol to match the pattern sync at the end of a line:
The first command matches every instance; the second only matches the instance at the end of
the line.
Previous
Next
8.5.6 Step 6
Use the period character . to match any single character. For example, execute the following
command to match any character followed by a 'y':
Previous
Next
8.5.7 Step 7
The pipe character, |, or "alternation operator", acts as an "or" operator. For example, execute
the following to attempt to match either sshd, root or operator:
Observe that the grep command does not recognize the pipe as the alternation operator by
default. The grep command is actually including the pipe as a plain character in the pattern to be
matched. The use of either grep -E or egrep will allow the use of the extended regular
expressions including alternation.
Previous
Next
8.5.8 Step 8
Use the -E switch to allow grep to operate in extended mode in order to recognize the alternation
operator:
Previous
Next
8.5.9 Step 9
Use another extended regular expression, this time with egrep with alternation in a group to
match a pattern. The strings nob and non will match:
Note: The parenthesis, ( ), were used to limit the "scope" of the | character. Without them, such
as nob|n, the pattern would have meant "match either nob or n”
Previous
Next
8.5.10 Step 10
The [ ] characters can also be used to match a single character, however unlike the period
character ., the [ ]characters are used to specify exactly what character you want to match. For
example, if you want to match a numeric character, you can specify [0-9]. Execute the following
command for a demonstration:
Note: The head command was used to limit the output of the grep command.
Previous
Next
8.5.11 Step 11
Suppose you want to search for a pattern containing a sequence of three digits. You can use {
} characters with a number to express that you want to repeat a pattern a specific number of
times; for example: {3} The use of the numeric qualifier requires the extended mode of grep:
Previous
Next
9.1 Introduction
This is Lab 9: Scripting Commands of the Linux Essentials. By performing this lab, students will
learn how to use the vi editor to create basic shell scripts using basic shell commands, variables
and control statements.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
9.2.1 Step 1
To create a new file, execute the following command:
vi myfile
Type an i to enter the “insert” mode of vi (more about this later). Then enter the following text:
Then press the Esc key to leave insert mode. Type :wq to write the file to disk and quit.
Note: Each of the previous commands will be covered in greater detail later in this lab. The
purpose of the previous step was to create a file to work with during this lab.
Previous
Next
9.2.2 Step 2
Invoke the vi editor to modify the file you created. When vi is invoked ,you are placed
in command mode by default:
vi myfile
Notice in the bottom-left, the file name, the number of lines, and the number of characters in the
file are displayed.
Previous
Next
9.2.3 Step 3
Press each of the following keys two times and observe how the cursor moves. Remember that
you are in command mode:
Key Function
Warning: If you type any other keys then those listed above, you may end up in insert mode.
Don't panic! Press the Esckey, then :q! + the Enter key. This should exit vi without saving any
changes. Then execute vi myfile and you are back in the vi editor!
Previous
Next
9.2.4 Step 4
More vi cursor navigation: Press the following keys and observe how the cursor moves:
Keys Function
Previous
Next
9.2.5 Step 5
Move the cursor to the beginning of the word "very" by pressing the following keys:
G
k
8l (that's the number eight followed by the letter "l")
The cursor should be on the letter v of the word "very" as shown below:
Previous
Next
9.2.6 Step 6
Delete the word “very” by issuing the command dw (delete word):
dw
Previous
Next
9.2.7 Step 7
Undo the last operation:
Previous
Next
9.2.8 Step 8
Delete two words:
2dw
Previous
Next
9.2.9 Step 9
Undo the last operation:
Previous
Next
9.2.10 Step 10
Delete four characters, one at a time:
xxxx
Previous
Next
9.2.11 Step 11
Undo the last 4 operations and recover the deleted characters:
4u
Previous
Next
9.2.12 Step 12
Delete 14 characters:
14x
Previous
Next
9.2.13 Step 13
Undo the last operation:
Previous
Next
9.2.14 Step 14
Delete the five characters to the left of the cursor (type 5 then Shift+x):
5X
Previous
Next
9.2.15 Step 15
Undo the last operation:
Previous
Next
9.2.16 Step 16
Delete the current line:
dd
Previous
Next
9.2.17 Step 17
Whatever was lasted deleted or yanked can be “pasted”. Paste the deleted lines below the
current line:
Previous
Next
9.2.18 Step 18
Undo the last two operations:
2u
Previous
Next
9.2.19 Step 19
Delete two lines, the current and the next:
2dd
Previous
Next
9.2.20 Step 20
Undo the last operation:
Previous
Next
9.2.21 Step 21
Move to the fourth word then delete from the current position to end of line Shift+D:
4w
D
The command d$ also deletes to end of line. The $ character, as seen earlier, advances to end of
line. Thus, d$ deletes to end of line.
Previous
Next
9.2.22 Step 22
Undo the last operation:
u
Your screen should look similar to the following:
Previous
Next
9.2.23 Step 23
Join two lines, the current and the next by typing a capital J (Shift+J):
Previous
Next
9.2.24 Step 24
Undo the last operation:
Previous
Next
9.2.25 Step 25
Copy (or “yank”) the current word:
yw
When you copy text, no change will take place on the screen.
Previous
Next
9.2.26 Step 26
Paste (or “put”) the copied word before the current cursor:
Previous
Next
9.2.27 Step 27
Undo the last operation:
Next
9.2.28 Step 28
Move to the first line, then join three lines:
1G
3J
Previous
Next
9.2.29 Step 29
Undo the last operation:
Previous
Next
9.2.30 Step 30
Search for and delete the word text (add a space after the word text):
:%s/text //g
Your screen should look similar to the following:
Previous
Next
9.2.31 Step 31
Navigate to beginning of file, then press i to enter insert mode to add text:
Keys Function
Previous
Next
9.2.32 Step 32
Exit insert mode and return to command mode by pressing the Escape key:
ESC
Previous
Next
9.2.33 Step 33
Move forward one space by pressing the lower case l to place the cursor on the W and toggle it to
lower case by pressing the tilde (~):
Keys Function
Previous
Next
9.2.34 Step 34
Save the file. Press the Esc key to ensure you are in command mode. Then type :w and
the Enter key:
:w
Previous
Next
9.2.35 Step 35
When you press Enter to commit the change, note the message in lower left indicating the file
has been written:
~
~
"myfile" 3 lines, 102 characters written
Previous
Next
9.2.36 Step 36
Navigate to the space between the word "powerful" and "editor" in the second line as shown
in the image below. You could press j followed by 10l or use the arrow keys:
Command Function/Keys
Previous
Next
9.2.37 Step 37
Append text to the right of the cursor by pressing the letter a. This moves the cursor to the right
and enters insert mode. Type the word text followed by a space as shown in image below:
Command Function/Keys
Previous
Next
9.2.38 Step 38
Exit insert mode by pressing the Esc key.
Previous
Next
9.2.39 Step 39
Open a blank line below the current line by typing a lowercase letter o:
Previous
Next
9.2.40 Step 40
Enter the following text:
Previous
Next
9.2.41 Step 41
Exit insert mode by pressing the Esc key.
Previous
Next
9.2.42 Step 42
Open a blank line above the current line by pressing uppercase O:
Previous
Next
9.2.43 Step 43
Enter the following text:
Previous
Next
9.2.44 Step 44
Exit insert mode by pressing the Esc key.
Previous
Next
9.2.45 Step 45
Save the file and close the vi editor using any one of the following methods that saves changes:
Command Function/Keys
ZZ Will save and close. Notice that no colon : is used in this case.
Previous
Next
9.2.46 Step 46
Once again open myfile using the vi editor:
vi myfile
Previous
Next
9.2.47 Step 47
Navigate to the third line, delete the third and fourth lines:
3G
2dd
Previous
Next
9.2.48 Step 48
Press the Esc key to confirm you are in command mode.
Previous
Next
9.2.49 Step 49
Quit the vi editor without saving your changes:
:q!
Previous
Next
9.2.50 Step 50
Open myfile with the vi editor:
vi myfile
Previous
Next
9.2.51 Step 51
Search forward for the word line. You’ll notice the cursor moves to the beginning of the first
instance of the word line as shown in image below:
/line
Next
9.2.52 Step 52
Search for the next instance of the word line by pressing the letter n:
Previous
Next
9.2.53 Step 53
Search backward for the word line. You’ll notice the cursor moves to the beginning of the
previous instance of the word line as shown in image below:
?line
Previous
Next
9.2.54 Step 54
Search for the previous instance of the word line by pressing the letter n. Since there are none
in this direction, vi will wrap around the document:
Previous
Next
9.2.55 Step 55
You will replace the word line with the word entry. When you press cw the word line will
disappear and you will be in insert mode:
cw
entry
Previous
Next
9.2.56 Step 56
Press Esc key to exit insert mode.
Previous
Next
9.2.57 Step 57
Add text at the beginning of a line. Enter insert mode again and add a line by pressing upper
case i:
Next
9.2.58 Step 58
Press the Esc key to return to command mode.
Previous
Next
9.2.59 Step 59
Add text at the end of a line (uppercase A). First move to the second line and add the
phrase Indeed!:
2G
A
[Space]Indeed!
Previous
Next
9.2.60 Step 60
Save your changes and exit vi:
:x
Previous
Next
9.3 Basic Shell Scripting
Shell scripting allows you to take a complex sequence of commands, place them into a file and
then run the file as a program. This saves you the time of having to repeatedly type a long
sequence of commands that you routinely use.
This lab will focus on how to create simple shell scripts. For the purpose of this lab, it is assumed
that you know how to use a text editor. Feel free to use the editor of your
choice: vi, nano, gedit or any other editor that you like.
Previous
Next
9.3.1 Step 1
To create a simple shell script, you just need to create a text file and add commands. Create a file
called sample.sh and add the following lines:
Previous
Next
9.3.2 Step 2
To make it clear that this is a BASH shell script, you need to include a special line at the top of
the file called a "shbang" (or "shebang"). This line starts with #! and then contains the path to the
BASH shell executable. Add the following line at the top of the sample.sh file:
#!/bin/bash
#!/bin/bash
echo "Hello there! Here is the calendar for this month:"
cal
~
~
Previous
Next
9.3.3 Step 3
One way that you can run this program is by typing bash before the filename. Execute the
following:
bash sample.sh
sysadmin@localhost:~$ bash sample.sh
Hello there! Here is the calendar for this month:
April 2016
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
sysadmin@localhost:~$
Previous
Next
9.3.4 Step 4
You can avoid having to type bash in front of the filename by making the file "executable" for all
users. Run the following commands:
ls -l sample.sh
chmod a+x sample.sh
ls -l sample.sh
./sample.sh
sysadmin@localhost:~$ ls -l sample.sh
-rw-rw-r-- 1 sysadmin sysadmin 73 Apr 9 22:44 sample.sh
sysadmin@localhost:~$ chmod a+x sample.sh
sysadmin@localhost:~$ ./sample.sh
Hello there! Here is the calendar for this month:
April 2016
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
sysadmin@localhost:~$
The chmod command is used to change permissions on the file so that the file can be executed.
Previous
Next
9.3.5 Step 5
A common feature used in scripting is "backquoting". With this technique, you can run a shell
command "within" another shell command. The outcome of the internal command will be returned
as an argument to the external command. Add the following to the bottom of the sample.sh file:
cat sample.sh
./sample.sh
sysadmin@localhost:~$ cat sample.sh
#!/bin/bash
echo "Hello there! Here is the calendar for this month:"
cal
echo "Today is" `date +%A`
sysadmin@localhost:~$ ./sample.sh
Hello there! Here is the calendar for this month:
April 2016
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Today is Friday
sysadmin@localhost:~$
Previous
Next
9.3.6 Step 6
You have been using ./ in front of the sample.sh filename to indicate that the file is in the
current directory. Execute the following to see how the shell would fail to find the file if you don't
use the ./:
sample.sh
sysadmin@localhost:~$ sample.sh
-bash: sample.sh: command not found
sysadmin@localhost:~$
Previous
Next
9.3.7 Step 7
Recall that the $PATH variable is used to search for commands that you type. Execute the
following to see the $PATHvariable for the sysadmin account:
echo $PATH
sysadmin@localhost:~$ echo $PATH
/home/sysadmin/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:
/bin:/usr/games
sysadmin@localhost:~$
Previous
Next
9.3.8 Step 8
Note that /home/sysadmin/bin is one of the directories in the $PATH variable. This is a great
place to put your shell scripts:
mkdir bin
mv sample.sh bin
sample.sh
sysadmin@localhost:~$ mkdir bin
sysadmin@localhost:~$ mv sample.sh bin
sysadmin@localhost:~$ sample.sh
Hello there! Here is the calendar for this month:
April 2016
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Today is Friday
sysadmin@localhost:~$
Previous
Next
Enter this column into drive.sh This column describes the code (don't enter into the file)
When following the instructions provided, you are to enter the text from the left column into the
specified file (drive.sh in the example above). The right column is used to describe specific
lines in the program. The pound sign # character is used because in a shell script, you can place
comments within your program by using a # character.
Previous
Next
9.4.1 Step 1
Scripts that are more complex may make use of conditional execution. A conditional expression,
like the if statement, can make use of the outcome of a command called test.
The test statement compares two numbers (or two strings) for things like "equal to", "less than",
etc.
Create the following file (drive.sh) and make it executable to see how
the if and test statements work. Begin by placing the following in drive.sh:
Enter this column into drive.sh This column describes the code (don't enter into the f
#!/bin/bash
read age # read user input and place in the $age variable
if test $age -lt 16 # test $age -lt 16 returns "true" if $age is numerically le
then
echo "You are not old enough to drive." # executes when test is true
else
cat drive.sh
chmod a+x drive.sh
./drive.sh
Verbally, you could read the if statement as "If $age is less than 16, then echo 'You are not old
enough to drive', else echo 'You can drive!'". The fi ends the if statement.
Note: $age must be an integer value. If not, the program will crash.
Previous
Next
9.4.2 Step 2
The test statement is automatically called when you place its arguments within square brackets [
] surrounded by spaces. Modify the if line of drive.sh so it looks like the following:
if [ $age -lt 16 ]
cat drive.sh
./drive.sh
To see a full list of test conditions, run the command man test.
Important: There must be spaces around the square brackets. [$age -lt 16] would fail, but [
$age -lt 16 ]would work.
Previous
Next
9.4.3 Step 3
You can also use the outcome of other shell commands as they all return "success" or "failure".
For example, create and run the following program, which can be used to determine if a user
account is on this system. Add the following to check.sh:
#!/bin/bash
echo "Enter a username to check: "
read name
if grep $name /etc/passwd > /dev/null
then
echo "$name is on this system"
else
echo "$name does not exist"
fi
When prompted for a username, give the value of "root". Execute the command again
(./check.sh) and provide the value of "bobby". Your screen should look like the following:
sysadmin@localhost:~$ cat check.sh
#!/bin/bash
echo "Enter a username to check: "
read name
if grep $name /etc/passwd > /dev/null
then
echo "$name is on this system"
else
echo "$name does not exist"
fi
sysadmin@localhost:~$ chmod a+x check.sh
sysadmin@localhost:~$ ./check.sh
Enter a username to check:
root
root is on this system
sysadmin@localhost:~$ ./check.sh
Enter a username to check:
bobby
bobby does not exist
sysadmin@localhost:~$
Previous
Next
9.4.4 Step 4
Another common conditional statement is called the while loop. This statement is used to
execute code repeatedly as long as a conditional check returns "true". Begin by placing the
following in a file named num.sh:
Enter this column into num.sh This column describes the code (don't enter in
#!/bin/bash
read num
Enter this column into num.sh This column describes the code (don't enter in
while [ $num -le 100 ] # Execute code from "do" to "done if test cond
do
read num
When prompted for a number, enter 25. When prompted again, enter 99. Finally, enter 101 when
prompted for a number the third time. Your screen should look like the following:
If the conditional check for the while statement ( [ $num -le 100 ] ) returns true, then the
statements between doand done are executed.
Once those statements have completed executing, the conditional check for the while statement
is checked again. If true again, then again the statements between do and done are executed.
This will continue repeating until the while condition returns false, or when the value is greater
than 100.
Previous
Next
9.4.5 Step 5
Scripting code is part of the BASH shell, which means you can use these statements on the
command line just like you use them in a shell script. This can be useful for a statement like
the for statement, a statement that will assign a list of values one at a time to a variable. This
allows you to perform a set of operations on each value. For example, run the following on the
command line:
Note that the wc command was run three times: once for /etc/passwd, once
for /etc/hosts and once for /etc/group.
Previous
Next
9.4.6 Step 6
Often the seq command is used in conjunction with the for statement. The seq command can
generate a list of integer values, for instance from 1 to 10. For example, run the following on the
command line to create 12 files named test1, test2, test3, etc. (up to test12):
ls
for num in `seq 1 12`
do
touch test$num
done
ls
sysadmin@localhost:~$ ls
Desktop Downloads Pictures Templates check.sh num.sh
Documents Music Public Videos drive.sh
sysadmin@localhost:~$ for num in `seq 1 12`
> do
> touch test$num
> done
sysadmin@localhost:~$ ls
Desktop Music Templates drive.sh test10 test2 test5 test8
Documents Pictures Videos num.sh test11 test3 test6 test9
Downloads Public check.sh test1 test12 test4 test7
sysadmin@localhost:~$
Previous
Next
10.1 Introduction
This is Lab 10: Understanding Computer Hardware. By performing this lab, students will learn
about commands to display information about the computer's hardware.
In this lab, you will perform the following tasks:
Use commands to list hardware.
Previous
Next
Previous
Next
10.2.1 Step 1
In order to determine the type of CPU execute the lscpu command:
lscpu
Being able to display CPU information can be important when trying to determine if more
advanced Linux features can be used on your system. For even more details about your CPU(s),
you can examine the /proc/cpuinfo file, especially, the "flags" that are listed that determine
whether or not your CPU has certain features.
Previous
Next
10.2.2 Step 2
View the /proc/cpuinfo file:
cat /proc/cpuinfo
Previous
Next
10.2.3 Step 3
To discover how much RAM and swap space is being used, use the free command:
free -m
free -g
The output shows the amount of memory in megabytes when the -m option is used and in
gigabytes when the -g option is used:
In the output above, you can see that the system has 16049 megabytes (roughly 15 gigabytes) of
physical memory (RAM). Of that only 1066 megabytes are being used, a good sign that you have
enough memory for your system's needs.
In the event that you run out of memory, Swap is used. Swap is hard drive space that is used to
temporarily store data that is supposed to be stored in RAM.
Previous
Next
10.2.4 Step 4
To see what devices are connected to the PCI bus, use the lspci command:
lspci
Notice from the partial output below, that many of the devices connected to the system board are
displayed:
The output of the lspci command can be very important to identify devices that are not
supported by the Linux kernel. Some devices like video cards may only provide basic functionality
without installing proprietary driver software.
Previous
Next
10.2.5 Step 5
Use the lspci command with the -k option to show devices along with the kernel driver and
modules used:
Previous
Next
10.2.6 Step 6
Attempt to list the USB connected devices:
lsusb
The output of this command is unusual since no USB devices are detected:
sysadmin@localhost:~$ lsusb
unable to initialize libusb: -99
sysadmin@localhost:~$
Due to this system being virtualized, the USB devices do not appear as they normally would
when executing the lsusbcommand. Normally, if USB devices are present, it would have shown
something like this:
sysadmin@localhost:~$ lsusb
Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
sysadmin@localhost:~$
HAL is the Hardware Abstraction Layer. The daemon for HAL is hald, which gathers information
about devices connected to the system. When events occur that somehow change the state of
the connected devices, then hald broadcasts this information to any processes that have
registered for the events. On systems that use HAL, the lshal command will be able to list the
devices of that system.
Previous
Next
10.2.7 Step 7
For hardware to function, the Linux kernel usually loads a driver or module. Use
the lsmod command to view the currently loaded modules:
lsmod
Partial output of the command is shown below. The first column is the module name, and the
second is the amount of memory used by the module. The number in the "Used by" column
indicates how many other modules are using the module. The names of the other modules using
the module may also be listed in the "Used by" column, but is often incomplete:
Previous
Next
10.2.8 Step 8
The system board of many computers contains what is known as BIOS, or a Basic Input and
Output System. System Management BIOS, or SMBIOS, is a standard defining the data
structures and how to communicate information about computer hardware.
The dmidecode command is able to read and print the information from the SMBIOS of many
systems. We will not demonstrate the command here, since it does not function properly within a
virtual environment.
The fdisk command can be used in two ways: interactively and non-interactively.
When the -l option is used with fdisk, then the command will non-interactively list block
devices, which includes disks (hard drives) and logical volumes.
Without the -l option the fdisk command enters an interactive mode that is typically used to
modify partitions on a disk device.
Previous
Next
10.2.9 Step 9
Execute the fdisk command to list the disk devices non-interactively, in sectors, and without
DOS compatibility warnings:
fdisk -cul
The partial output of this command below shows the first couple of
disks, /dev/sda and /dev/sdb, and their partitions. The third disk, /dev/sdc, and the logical
volumes that followed it have been omitted:
The -u option causes the fdisk command to display units in sectors instead of cylinders. The -
c option prevents the fdiskcommand from printing warnings that affect DOS compatibility.
Previous
Next
11.1 Introduction
This is Lab 11: Linux Data Locations. By performing this lab, students will learn about the
locations of kernel information, process information, libraries, log files, and software packages.
In this lab, you will perform the following tasks:
Next
Previous
Next
11.2.1 Step 1
In this task, you will examine some of the files contained in the /proc directory:
ls /proc
sysadmin@localhost:~$ ls /proc
1 cpuinfo kallsyms mpt sysrq-trigger
19 crypto kcore mtrr sysvipc
23 devices key-users net thread-self
25 diskstats keys pagetypeinfo timer_list
41 dma kmsg partitions timer_stats
50 driver kpagecount sched_debug tty
62 execdomains kpageflags schedstat uptime
74 fb loadavg scsi version
acpi filesystems locks self version_signature
buddyinfo fs mdstat slabinfo vmallocinfo
bus interrupts meminfo softirqs vmstat
cgroups iomem misc stat zoneinfo
cmdline ioports modules swaps
consoles irq mounts sys
sysadmin@localhost:~$
Recall that the directories that have numbers for names represent running processes on the
system. The first process is always /sbin/init, so the directory /proc/1 will contain files with
information about the running init process.
The cmdline file inside the process directory (/proc/1/cmdline, for example) will show the
command that was executed. The order in which other processes are started varies greatly from
system to system. Since the content of this file does not contain a new line character,
an echo command will be executed to cause the prompt to go to a new line.
Previous
Next
11.2.2 Step 2
Use cat and then ps to view information about the /sbin/init process (Process IDentifier
(PID) of 1):
Note: The echo command in this example is executed immediately after the cat command. Since
it has no argument, it functions only to put the following command prompt on a new line. Execute
the cat command alone to see the difference.
sysadmin@localhost:~$ ps -p 1
PID TTY TIME CMD
1 ? 00:00:00 init
The other files in the /proc directory contain information about the operating system. The
following tasks will be used to view and modify these files.
Previous
Next
11.2.3 Step 3
View the /proc/cmdline file to see what arguments were passed to the kernel at boot time:
cat /proc/cmdline
Previous
Next
Previous
Next
11.3.1 Step 1
From the terminal, type the following command:
The output of the ping is being redirected to the /dev/null file (which is commonly known as
the bit bucket).
Notice that the terminal appears to hang up at this command. This is due to running this
command in the “foreground”. The system will continue to ping until the process is terminated or
suspended by the user.
Previous
Next
11.3.2 Step 2
Terminate the foreground process by pressing Ctrl-C.
sysadmin@localhost:~$ ping localhost > /dev/null
^C
sysadmin@localhost:~$
Previous
Next
11.3.3 Step 3
Next, to start the same process in the background, type:
By adding the ampersand & to the end of the command, the process is started in the background
allowing the user to maintain control of the terminal.
An easier way to enter the above command would be to take advantage of the command history.
You could have pressed the Up Arrow Key ↑ on the keyboard, add a Space and & to the end of
the command and then pressed the Enter key. This is a time-saver when entering similar
commands.
Notice that the previous command returns the following information:
[1] 158
This means that this process has a job number of 1 (as demonstrated by the output of [1]) and a
Process ID (PID) of 158. Each terminal/shell will have unique job numbers. The PID is system-
wide; each process has a unique ID number.
This information is important when performing certain process manipulations, such as stopping
processes or changing their priority value.
Note: Your Process ID will likely be different than the one in the example.
Previous
Next
11.3.4 Step 4
To see which commands are running in the current terminal, type the following command:
jobs
Your output should be similar to the following:
sysadmin@localhost:~$ jobs
[1]+ Running ping localhost > /dev/null &
Previous
Next
11.3.5 Step 5
Next, start another ping command in the background by typing the following:
Notice the different job number and process ID for this new command.
Previous
Next
11.3.6 Step 6
Now, there should be two ping commands running in the background. To verify, issue
the jobs command again:
jobs
sysadmin@localhost:~$ jobs
[1]- Running ping localhost > /dev/null &
[2]+ Running ping localhost > /dev/null &
Previous
Next
11.3.7 Step 7
Once you have verified that two ping commands are running, bring the first command to the
foreground by typing the following:
fg %1
sysadmin@localhost:~$ fg %1
ping localhost > /dev/null
Previous
Next
11.3.8 Step 8
Notice that, once again, the ping command has taken control of the terminal. To suspend
(pause) the process and regain control of the terminal, type Ctrl-Z:
sysadmin@localhost:~$ fg %1
ping localhost > /dev/null
^Z
[1]+ Stopped ping localhost > /dev/null
Previous
Next
11.3.9 Step 9
To have this process continue executing in the background, execute the following command:
bg %1
sysadmin@localhost:~$ bg %1
[1]+ ping localhost > /dev/null &
Previous
Next
11.3.10 Step 10
Issue the jobs command again to verify two running processes :
jobs
Your output should be similar to the following:
sysadmin@localhost:~$ jobs
[1]- Running ping localhost > /dev/null &
[2]+ Running ping localhost > /dev/null &
Previous
Next
11.3.11 Step 11
Next, start one more ping command by typing the following:
Previous
Next
11.3.12 Step 12
Issue the jobs command again to verify three running processes :
jobs
sysadmin@localhost:~$ jobs
[1] Running ping localhost > /dev/null &
[2]- Running ping localhost > /dev/null &
[3]+ Running ping localhost > /dev/null &
Previous
Next
11.3.13 Step 13
Using the job number, stop the last ping command with the kill command and verify it was
stopped executing the jobscommand:
kill %3
jobs
sysadmin@localhost:~$ kill %3
sysadmin@localhost:~$ jobs
[1] Running ping localhost > /dev/null &
[2]- Running ping localhost > /dev/null &
[3]+ Terminated ping localhost > /dev/null
Previous
Next
11.3.14 Step 14
Finally, you can stop all of the ping commands with the killall command. After executing
the killall command, wait a few moments, and then run the jobs command to verify that all
processes have stopped:
killall ping
jobs
Previous
Next
Previous
Next
11.4.1 Step 1
From the terminal window, type the following commands:
Make note of the PIDs output by the above commands! They will be different than the
examples that we are providing. You will use the PIDs in subsequent steps.
Previous
Next
11.4.2 Step 2
Next, start the top command by typing the following in the terminal:
top
Previous
Next
11.4.3 Step 3
The top command is an interactive program, which means that you can issue commands within
the program. You will use the top command to kill the ping processes. First type the letter k.
Notice a prompt has appeared underneath Swap:
Previous
Next
11.4.4 Step 4
At the PID to kill: prompt, type the PID of the first running ping process, then press Enter.
Notice that the prompt changes as below:
Previous
Next
11.4.5 Step 5
At the Kill PID with signal [15]: prompt, enter the signal to send to this process. In this
case, just press the Enterkey to use the default signal. Notice that the first ping command is
removed and only one ping command remains in the listing (you may need to wait a few seconds
as the top command refreshes):
Consider This
There are several different numeric values that can be sent to a process. These are predefined
values, each with a different meaning. If you want to learn more about these values, type man
kill in a terminal window.
The prompt indicates that the default signal is the terminate signal indicated bySIGTERM or the
number 15.
Previous
Next
11.4.6 Step 6
Next, kill the remaining ping process as before, except this time, at the signal prompt Kill PID
with signal [15]:prompt, use a value of 9 instead of accepting the default of 15.
Press Enter to accept then entry.
Consider This
The kill signal 9 or SIGKILL is a "forceful" signal that cannot be ignored, unlike the default value
of 15. Notice that all references to the ping command are now removed from top.
Previous
Next
11.4.7 Step 7
Type q to exit the top command. The following screen reflects that both ping commands were
terminated:
Previous
Next
Previous
Next
11.5.1 Step 1
To begin, type the following commands in the terminal:
The sleep command is typically used to pause a program (shell script) for a specific period of
time. In this case it is used just to provide a command that will take a long time to run.
Make sure to note the PIDs on your system of the sleep processes for the next steps! Your PIDs
will be different than those demonstrated in the lab.
Previous
Next
11.5.2 Step 2
Next, determine which jobs are currently running by typing:
jobs
sysadmin@localhost:~$ jobs
[1]- Running sleep 888888 &
[2]+ Running sleep 888888 &
sysadmin@localhost:~$
Previous
Next
11.5.3 Step 3
Now, use the kill command to stop the first instance of the sleep command by typing the
following (substitute PID with the process id of your first sleep command). Also, execute jobs to
verify the process has been stopped:
kill PID
jobs
sysadmin@localhost:~$ ps
PID TTY TIME CMD
62 ? 00:00:00 bash
89 ? 00:00:00 sleep
90 ? 00:00:00 sleep
91 ? 00:00:00 ps
sysadmin@localhost:~$ kill 89
sysadmin@localhost:~$ jobs
[1]- Terminated sleep 888888
[2]+ Running sleep 888888 &
sysadmin@localhost:~$
Helpful Hint: If you can't remember the PID of the first process, just type the ps (process)
command, as shown above.
Previous
Next
11.5.4 Step 4
Next, use the pkill command to terminate the remaining sleep command, using the name of
the program rather than the PID:
Previous
Next
Previous
Next
11.6.1 Step 1
Start up a background process using ping and view current processes using the ps command:
Make note of the PID of the ping, you will use the PID in a subsequent step.
Previous
Next
11.6.2 Step 2
Execute the ps command using the option -e, so all processes are displayed.
ps -e
sysadmin@localhost:~$ ps -e
PID TTY TIME CMD
1 ? 00:00:00 init
19 ? 00:00:00 rsyslogd
23 ? 00:00:00 cron
25 ? 00:00:00 sshd
41 ? 00:00:00 named
50 ? 00:00:00 login
62 ? 00:00:00 bash
98 ? 00:00:00 ping
100 ? 00:00:00 ps
Due to this environment being a virtualized operating system, there are far fewer processes than
what would normally be shown with Linux running directly on hardware.
Previous
Next
11.6.3 Step 3
Use the ps command with the -o option to specify which columns to output.
ps -o pid,tty,time,%cpu,cmd
Your output should be similar to the following:
sysadmin@localhost:~$ ps -o pid,tty,time,%cpu,cmd
PID TT TIME %CPU CMD
62 ? 00:00:00 0.0 -bash
98 ? 00:00:00 0.0 ping localhost
102 ? 00:00:00 0.0 ps -o pid,tty,time,%cpu,cmd
Previous
Next
11.6.4 Step 4
Use the --sort option to specify which column(s) to sort by. By default, a column specified for
sorting will be in ascending order, this can be forced with placing a plus + symbol in front of the
column name. To specify a descending sort, use the minus - symbol in front of the column name.
Sort the output of ps by %mem:
Previous
Next
11.6.5 Step 5
While the ps command can show the percentage of memory that a process is using,
the free command will show overall system memory usage:
free
sysadmin@localhost:~$ free
total used free shared buffers cached
Mem: 65969788 6242744 59727044 0 300852 1062284
-/+ buffers/cache: 4879608 61090180
Swap: 2097148 0 2097148
Previous
Next
11.6.6 Step 6
Stop the ping command with the following kill command and verify with the jobs command:
kill PID
jobs
sysadmin@localhost:~$ kill 98
sysadmin@localhost:~$ jobs
[1]+ Terminated ping localhost > /dev/null
Previous
Next
Previous
Next
11.7.1 Step 1
Because the next few commands that you will run in this lab require superuser rights, use
the su command to switch to the root account:
su - root
{Enter the password: netlab123}
sysadmin@localhost:~$ su - root
Password:
root@localhost:~#
Previous
Next
11.7.2 Step 2
System logs are stored in the /var/log directory. List the files in this directory:
ls /var/log
root@localhost:~# ls /var/log
alternatives.log boot cron.log faillog lastlog news wtm
p
apt bootstrap.log dmesg fsck mail.err syslog
auth.log btmp dpkg.log kern.log mail.log upstart
root@localhost:~#
Previous
Next
11.7.3 Step 3
Each log file represents a service or feature. For example, the auth.log file displays information
regarding authorization or authentication, such as user login attempts. New data is stored at the
bottom of the file. Execute the following commands to see an example:
ssh localhost
{At the first prompt, type yes}
{At the second prompt, type abc}
{At the third prompt, type abc}
{At the fourth prompt, type abc}
tail -5 /var/log/auth.log
root@localhost:~# ssh localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is 5f:e2:43:0f:f9:26:e5:d5:77:ba:9e:95:72:9e:ee:64.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
root@localhost's password:
Permission denied, please try again.
root@localhost's password:
Permission denied, please try again.
root@localhost's password:
Permission denied (publickey,password).
root@localhost:~# tail -5 /var/log/auth.log
Apr 8 20:25:13 localhost sshd[117]: pam_unix(sshd:auth): authentication fa
ilure; logname= uid=0 euid=0 tty=ssh ruser= rhost=localhost user=root
Apr 8 20:25:16 localhost sshd[117]: Failed password for root from ::1 port
58940 ssh2
Apr 8 20:25:28 sshd[117]: last message repeated 2 times
Apr 8 20:25:28 localhost sshd[117]: Connection closed by ::1 [preauth]
Apr 8 20:25:28 localhost sshd[117]: PAM 2 more authentication failures; lo
gname= uid=0 euid=0 tty=ssh ruser= rhost=localhost user=root
root@localhost:~#
The ssh command was used to generated data in the /var/log/auth.log file. Note the failed
login attempts are logged in the /var/log/auth.log file.
Previous
Next
11.7.4 Step 4
To see another example of log entries, execute the following commands:
crontab -e
Then add the following line to the document (recall that i will allow you to enter the insert mode)
and then save and exit with ESC, :wq, Enter:
After you have completed the edits, view the log file for the crontab service:
crontab -l | tail -2
tail /var/log/cron.log
root@localhost:~# crontab -l | tail -2
# m h dom mon dow command
0 2 * * 0 who >> /tmp/whothere
root@localhost:~# tail /var/log/cron.log
Apr 8 17:33:32 localhost /usr/sbin/cron[22]: (CRON) INFO (pidfile fd = 3)
Apr 8 17:33:32 localhost /usr/sbin/cron[23]: (CRON) STARTUP (fork ok)
Apr 8 17:33:32 localhost /usr/sbin/cron[23]: (CRON) INFO (Running @reboot
jobs)
Apr 8 18:17:01 localhost /USR/SBIN/CRON[79]: (root) CMD ( cd / && run-pa
rts -
-report /etc/cron.hourly)
Apr 8 19:17:02 localhost /USR/SBIN/CRON[82]: (root) CMD ( cd / && run-pa
rts -
-report /etc/cron.hourly)
Apr 8 20:17:01 localhost /USR/SBIN/CRON[99]: (root) CMD ( cd / && run-pa
rts -
-report /etc/cron.hourly)
Apr 8 20:31:18 localhost crontab[121]: (root) BEGIN EDIT (root)
Apr 8 20:32:42 localhost crontab[121]: (root) REPLACE (root)
Apr 8 20:32:42 localhost crontab[121]: (root) END EDIT (root)
Apr 8 20:33:19 localhost crontab[132]: (root) LIST (root)
root@localhost:~#
Previous
Next
11.7.5 Step 5
View the last five lines of the file /var/log/dmesg to see kernel messages from boot time and
execute the dmesgcommand piped to the tail command to view the last five kernel messages:
tail -5 /var/log/dmesg
dmesg | tail -5
root@localhost:~# tail -5 /var/log/dmesg
[ 2.922003] type=1400 audit(1386098331.347:10): apparmor="STATUS" operat
ion="profile_load" name="/usr/sbin/tcpdump" pid=848 comm="apparmor_parser"
[ 2.989112] Bridge firewalling registered
[ 3.007035] ip_tables: (C) 2000-2006 Netfilter Core Team
[ 3.010733] nf_conntrack version 0.5.0 (16384 buckets, 65536 max)
[ 3.020096] input: ImPS/2 Generic Wheel Mouse as /devices/platform/i8042
/serio1/input/input2
root@localhost:~# dmesg | tail -5
[279447.718341] device veth0pl17180 left promiscuous mode
[279447.718408] br998ad950-b830: port 1(veth0pl17180) entered disabled stat
e
[279448.519497] bre2e72298-4b5e: port 1(veth0pl17664) entered disabled stat
e
[279448.525087] device veth0pl17664 left promiscuous mode
[279448.525091] bre2e72298-4b5e: port 1(veth0pl17664) entered disabled stat
e
root@localhost:~#
Right about now you are likely thinking "what do all of these messages actually mean?". The
answer to that question isn't a simple one, however the point behind this lesson isn't to explain
the meaning of all of the log messages, but rather to learn where to find log messages.
As you gain more experience in Linux, you will start to troubleshoot problems. In most cases the
first place you want to look is the log files.
In order to provide you a realistic troubleshooting example, follow the next set of tasks.
Previous
Next
11.7.6 Step 6
Enter the following command to disable the ability of the sysadmin user from
creating crontab entries and exit back to the sysadmin user:
Previous
Next
11.7.7 Step 7
Attempt to execute the following crontab command:
crontab -e
sysadmin@localhost:~$ crontab -e
You (sysadmin) are not allowed to use this program (crontab)
See crontab(1) for more information
sysadmin@localhost:~$
Note: This command fails because of the entry in the /etc/cron.deny. If a username exists in
this file, then that user can not use the crontab command.
Previous
Next
11.7.8 Step 8
Instead of switching users to root with the su command, use sudo to execute the following
command with root privileges:
As you can see from the last line of the output of the tail command, the sysadmin user is not
allowed to use the crontabcommand.
Previous
Next
Previous
Next
11.8.1 Step 1
When executed as the root user, the ldconfig command can be used to update the cache and
the symbolic links for the shared libraries on the system. As an ordinary user, you will execute
the ldconfig command to print the list of shared libraries:
ldconfig -p | less
Previous
Next
11.8.2 Step 2
In order to view what libraries are linked to an executable, such as /bin/bash, execute
the ldd command:
ldd /bin/bash
Previous
Next
12.1 Introduction
This is Lab 12: Poking the Network. By performing this lab, students will learn about the
configuration of your computer on the network.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
12.2.1 Step 1
In order to determine your Internet Protocol (IP) address, execute the ifconfig command:
sysadmin@localhost:~$ ifconfig
eth0 Link encap:Ethernet HWaddr 3a:3b:65:10:f6:43
inet addr:192.168.1.2 Bcast:0.0.0.0 Mask:255.255.255.0
inet6 addr: fe80::383b:65ff:fe10:f643/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:15 errors:0 dropped:0 overruns:0 frame:0
TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1206 (1.2 KB) TX bytes:690 (690.0 B)
Previous
Next
12.2.2 Step 2
Having an IP address will allow your system to communicate with other systems on the same
network. With routing devices you are able to communicate with systems on other networks. To
view the table of routing information, use the route command:
route
route -n
sysadmin@localhost:~$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Ifa
ce
192.168.1.0 * 255.255.255.0 U 0 0 0 eth
0
sysadmin@localhost:~$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Ifa
ce
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth
0
sysadmin@localhost:~$
Notice that the output of the first route command, names were provided for some items (like *). In
the output of the second route command, numbers were provided in place of names, the result
of using the -n option to the route command.
When connecting to other computers, either an IP address or a hostname may be used.
Hostnames can be used if they are entered into the /etc/hosts file along with their associated
IP address or if a Domain Name Server (DNS) provides IP address to host name translation.
A couple of names that are commonly in the /etc/hosts file are localhost,
and localhost.localdomain, both of which are used to refer to the current machine.
Previous
Next
12.2.3 Step 3
Verify that the IP address 127.0.0.1 has an entry in the /etc/hosts file:
The ping command may be used to tell if a system is presently connected to a network.
Sometimes, a system may be configured to not respond to ping requests. Therefore, the lack of
a response to a pingcommand does not mean a system is not connected to a network. A quick
response to a ping command does indicate, however that a system is connected to a network.
Previous
Next
12.2.4 Step 4
Test to see if the localhost machine will respond to four ping requests:
Previous
Next
12.2.5 Step 5
View the /etc/resolv.conf file to see if any nameserver entries exists:
cat /etc/resolv.conf
Previous
Next
12.2.6 Step 6
Use the dig command to resolve the localhost.localdomain name to an IP address:
dig localhost.localdomain
sysadmin@localhost:~$ dig localhost.localdomain
;; QUESTION SECTION:
;localhost.localdomain. IN A
;; ANSWER SECTION:
localhost.localdomain. 86400 IN A 127.0.0.1
;; AUTHORITY SECTION:
localdomain. 86400 IN NS localhost.localdomain.
sysadmin@localhost:~$
Notice the output shows that the first nameserver that was listed in
the /etc/resolv.conf file is the one that responded with the answer in the ANSWER
SECTION of the output.
Previous
Next
12.2.7 Step 7
You can use the dig command to resolve other fully qualified domain names. Use
the dig command to resolve the cserver.example.com hostname to an IP address:
dig cserver.example.com
sysadmin@localhost:~$ dig cserver.example.com
; <<>> DiG 9.8.1-P1 <<>> cserver.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57203
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1
;; QUESTION SECTION:
;cserver.example.com. IN A
;; ANSWER SECTION:
cserver.example.com. 86400 IN A 192.168.1.2
;; AUTHORITY SECTION:
example.com. 86400 IN NS example.com.
;; ADDITIONAL SECTION:
example.com. 86400 IN A 192.168.1.2
;; Query time: 990 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Apr 11 13:45:38 2016
;; MSG SIZE rcvd: 83
sysadmin@localhost:~$
A fully qualified domain name (FQDN) includes not just the hostname, but also the domain that
the hostname is "in". For the FQDN cserver.example.com, cserver is the hostname
and example.com is the domain.
Previous
Next
12.2.8 Step 8
Use the dig command to resolve the IP address 192.168.1.2 to a hostname:
dig -x 192.168.1.2
sysadmin@localhost:~$ dig -x 192.168.1.2
; <<>> DiG 9.8.1-P1 <<>> -x 192.168.1.2
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26791
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 1, ADDITIONAL: 1
;; QUESTION SECTION:
;2.1.168.192.in-addr.arpa. IN PTR
;; ANSWER SECTION:
2.1.168.192.in-addr.arpa. 86400 IN PTR cserver.example.com.
2.1.168.192.in-addr.arpa. 86400 IN PTR example.com.
;; AUTHORITY SECTION:
1.168.192.in-addr.arpa. 86400 IN NS example.com.
;; ADDITIONAL SECTION:
example.com. 86400 IN A 192.168.1.2
;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Apr 11 13:57:50 2016
;; MSG SIZE rcvd: 119
sysadmin@localhost:~$
Previous
Next
12.2.9 Step 9
The netstat command performs a large variety of tasks related to networking. To get an idea of
some of its capabilities, execute the command with the --help option:
netstat --help
sysadmin@localhost:~$ netstat --help
usage: netstat [-vWeenNcCF] [<Af>] -r netstat {-V|--version|-h|--he
lp
netstat [-vWnNcaeol] [<Socket> ...]
netstat { [-vWeenNac] -i | [-cWnNe] -M | -s }
One of the common uses of netstat is to determine which services are listening to or waiting for
an incoming connection. For example, a service that is used to allow users to perform remote or
network logins is called Secure SHell or SSH. SSH normally will listen to TCP port 22.
Well-known ports are the port numbers in the range of 0-1023, typically used by system
processes to provide network services. A list of service names and associated port numbers can
be found in the /etc/services file.
Previous
Next
12.2.10 Step 10
Use the netstat command to see if the TCP port for ssh, 22, has a process listening:
netstat -tl
netstat -tln
sysadmin@localhost:~$ netstat -tl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 example.com:domain *:* LISTEN
tcp 0 0 localhost:domain *:* LISTEN
tcp 0 0 *:ssh *:* LISTEN
tcp 0 0 localhost:953 *:* LISTEN
tcp6 0 0 [::]:domain [::]:* LISTEN
tcp6 0 0 [::]:ssh [::]:* LISTEN
tcp6 0 0 localhost:953 [::]:* LISTEN
sysadmin@localhost:~$
Previous
Next
12.2.11 Step 11
The -t option to the netstat command limits the listing to TCP ports; the -l option limits the
output to ports with listening services; the -n shows the network addresses numerically:
Previous
Next
13.1 Introduction
This is Lab 13: See Who's on your System. By performing this lab, students will be able to
monitor who has been attempting to log in to the system, and view any of their running
processes.
In this lab, you will perform the following tasks:
Learn the difference between the superuser account and regular user accounts.
View user account information.
Previous
Next
Previous
Next
13.2.1 Step 1
User and system accounts are defined in the /etc/passwd and /etc/shadow files. View the
first ten lines from the /etc/passwd file:
head /etc/passwd
Notice that this file contains a colon delimited database of all user and system accounts available
on this system.
User accounts are assigned to users, to allow them access to the operating system.
The sysadmin account that you used to log in to the system is a typical user account.
The root account is a special user account that has virtually unlimited access and control over
the system. It is sometimes referred to as the "superuser" account.
System accounts are used by the operating system or services running processes on it. By not
having these services run as the root user, the system is kept more secure by limiting the
damage that a comprised service account could cause. System accounts are never used directly
by regular users.
Previous
Next
13.2.2 Step 2
Use the grep command to view the record for your sysadmin account:
By using the grep command, the output only includes the account information for that one
username.
Another way to retrieve the account information for a user is by running the following
command: getent passwd username. The getent command has the advantage over
the grep command as it is also able to access user accounts that are not defined locally. In other
words, the getent command is able to get user information for users who may be defined on
network directory servers such as LDAP, NIS, Windows Domain, or Active Directory Domain
servers.
Previous
Next
13.2.3 Step 3
Use the getent command to retrieve the information about the sysadmin:
getent passwd sysadmin
sysadmin@localhost:~$ getent passwd sysadmin
sysadmin:x:1001:1001:System Administrator,,,,:/home/sysadmin:/bin/bash
sysadmin@localhost:~$
Note: In this case we don't have any network accounts, so the output displayed is just like looking
at the /etc/passwd file.
Previous
Next
13.2.4 Step 4
You can view the documentation of the fields in the /etc/passwd file with the following
command:
man 5 passwd
Remember while viewing a man page, press Enter to move forward line by line, Space page by
page and q to quit.
account:password:UID:GID:GECOS:directory:shell
Previous
Next
13.2.5 Step 5
You can view account information for your account, or a specified user account, using
the id command:
id
id root
sysadmin@localhost:~$ id
uid=1001(sysadmin) gid=1001(sysadmin) groups=1001(sysadmin),4(adm),27(sudo
sysadmin@localhost:~$ id root
uid=0(root) gid=0(root) groups=0(root)
sysadmin@localhost:~$
The output of the commands shows your user identity as a number and
name: uid=1001(sysadmin). It also displays your primary group
identity, gid=1001(sysadmin), and all the groups that you belong
to, groups=1001(sysadmin), 4(adm)and 27(sudo). In this case, your user account only
belongs to three groups.
The file /etc/group, together with /etc/passwd, determines your group memberships. Your
default primary group is determined by matching your GID found in /etc/passwd to the GID
defined for a group in the /etc/group. Any secondary group memberships are defined in
the /etc/group file.
The format of entries in the /etc/group file for each line is:
group_name:password:GID:user_list
Previous
Next
13.2.6 Step 6
The getent command can retrieve information about entries in the /etc/group file.
Use getent to retrieve information about the sysadmin and adm groups:
Previous
Next
13.2.7 Step 7
Two commands with simple output for understanding your identity are whoami and groups.
The groups command can also be used get the list of groups for another user. Use
the whoami and groups command for your account and the groups command for the root user:
whoami
groups
groups root
sysadmin@localhost:~$ whoami
sysadmin
sysadmin@localhost:~$ groups
sysadmin adm sudo
sysadmin@localhost:~$ groups root
root : root
sysadmin@localhost:~$
Previous
Next
Previous
Next
13.3.1 Step 1
Use the who command to get the current list of users on the system:
who
sysadmin@localhost:~$ who
sysadmin tty Apr 11 14:32
sysadmin@localhost:~$
Previous
Next
13.3.2 Step 2
Use the w command to get a more detailed view of the users who are currently on your system:
sysadmin@localhost:~$ w
15:17:08 up 6 days, 15 min, 1 user, load average: 0.39, 0.34, 0.37
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
sysadmin console 14:32 4.00s 0.16s 0.00s w
sysadmin@localhost:~$
A summary of how long the system has been running, how many users are logged in and the
system load averages for the past 1, 5, and 15 minutes.
An entry for each user with their login name, tty name, host, login time, idle time, JCPU (CPU
time used by background jobs), PCPU (CPU time used by the current process) and what is
executing on the current command line.
Previous
Next
Previous
Next
13.4.1 Step 1
To set up the sudo command for regular users, use the visudo command. This requires root
access as the visudo command will fail when regular users execute the command. Attempt to
configure access to the sudo command:
visudo
sysadmin@localhost:~$ visudo
visudo: /etc/sudoers: Permission denied
visudo: /etc/sudoers: Permission denied
sysadmin@localhost:~$
The output shows that the visudo command failed because it attempts to modify
the /etc/sudoers file, a file that regular users can't modify due to permissions. This file controls
access to the sudo command and should never be modified directly, but rather with
the visudo command.
Previous
Next
13.4.2 Step 2
Switch users to the root user and provide the root password of netlab123 when prompted:
su -
netlab123
sysadmin@localhost:~$ su -
Password:
root@localhost:~#
The dash or hyphen after the su command is an abbreviation for the option -l, which makes the
login performed by su a complete login by executing the login scripts belonging to the root user.
Without the -, or -l, the su command will switch your user identity, but it will not execute the login
scripts of the new user. This can cause some problems, especially when switching to
the root account. In most cases when you switch users you want a complete login to be
performed so that environment variables, functions and aliases that are normally initialized for a
user will be initialized.
Previous
Next
13.4.3 Step 3
Now that you are logged in as the root user, you should be able to execute the command to
configure sudo access:
visudo
root@localhost:~# visudo
Previous
Next
13.4.4 Step 4
To enable basic access to the use of the sudo command, an entry must be added to
the /etc/sudoers file that you are now editing. Since you are in the vi editor by default, type
the following to find this entry:
#includedir /etc/sudoers.d
sysadmin ALL=(ALL) ALL
-- INSERT --
If you type the data into the file correctly, you should be placed back at a shell prompt.
However, if upon exiting the edit, you are presented with a prompt that says "What now?", then
press Enter to see your choices. It is recommended that you type x to exit without saving
changes to the sudoers file and repeat this step over.
Previous
Next
13.4.5 Step 5
Return to the sysadmin account to verify that sudo provides root access by typing the following:
exit
root@localhost:~# exit
logout
sysadmin@localhost:~$
Previous
Next
13.4.6 Step 6
Try to view the first few lines of /etc/shadow file, a file that contains the users' encrypted
passwords and information about aging them:
head -3 /etc/shadow
sysadmin@localhost:~$ head -3 /etc/shadow
head: cannot open `/etc/shadow' for reading: Permission denied
sysadmin@localhost:~$
Notice the error message the head command displays. This is because the sysadmin user has
no rights to view this file. The root user, however, can display this file.
Previous
Next
13.4.7 Step 7
Notice that the permissions on the /etc/shadow file indicate that only members of
the shadow group have permission to view the file:
ls -l /etc/shadow
Keep in mind that the root user can view any file. This is due to the root account having
special privileges that transcend regular file permissions.
sysadmin@localhost:~$ ls -l /etc/shadow
-rw-r----- 1 root shadow 838 Mar 14 17:34 /etc/shadow
sysadmin@localhost:~$
Previous
Next
13.4.8 Step 8
Use the sudo command to view the first few lines of /etc/shadow file:
Important Note: The password that you provided was for your sysadmin account, not
the root account. Once sudohas been configured for your account, you don't need to know
the root password to run sudo commands as the rootuser.
Previous
Next
14.1 Introduction
This is Lab 14: Creating a User. By performing this lab, students will learn about how to create a
new user account, establish the initial password for this account, and make other modifications
such as making them a member of a secondary group.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
14.2.1 Step 1
In order to administer the user and group accounts, you will want to switch users to
the root account with the following command:
su -
(Provide the root password "netlab123" when prompted)
sysadmin@localhost:~$ su -
Password:
root@localhost:~#
Previous
Next
14.2.2 Step 2
Use the groupadd command to create a group called "research":
groupadd -r research
root@localhost:~# groupadd -r research
root@localhost:~#
The research group that was just added was added in the reserved range (between 1-999)
because the -r option was used. Group Identifiers (GIDs) are automatically assigned with a value
of less than the lowest normal user UID with this option. The groupadd command modifies
the /etc/group file where group account information is stored.
The groupmod command could be used with a -n option to change the name of this group or
the -g option in order to change the GID for this group. The groupdel command can be used to
delete this group, as long as it has not been made the primary group for a user.
Previous
Next
14.2.3 Step 3
Use a getent command to retrieve information about the new group:
Your output should appear similar to the following, although the GID that was assigned may be
different:
Now that the research group has been created, existing or new users can be made a member
of this group. The usermodoption -G must have a comma separated list of all secondary groups
the user is to belong.
When usermod is used with the -a and -G options, then only the new group will need to be
specified and it will be added to the existing secondary group memberships.
Previous
Next
14.2.4 Step 4
Use the usermod command to add the research group as a secondary group for
the sysadmin user:
Users who are actively logged into the system will not be able to use any new group
memberships until the next time they log into the system.
Previous
Next
14.2.5 Step 5
There are several commands that could be used to verify the new group membership. Use
the groups, id and getentcommands to verify the sysadmin's membership:
groups sysadmin
id sysadmin
getent group research
The useradd command will create a new user account and, in Red Hat-based distributions, a
new group for that user. This new group will be named after the user and that will be their primary
group.
Red Hat-based distributions use what is known as "User Private Groups", or UPG, each user is a
primary member of their own private group.
For distributions that do not use UPG, all new users belong to the users group as their primary
group.
Previous
Next
14.2.6 Step 6
Create a new user named student who is a secondary member of the research group and a
primary member of their own private group. Use a comment of Linux Student that will appear
as the full name of the user when they do a graphical login. Make sure that their home directory
will be created by specifying the -m option:
The user's account information is stored in the /etc/passwd and /etc/shadow files. The
user's group information can be found in /etc/passwd and /etc/group file.
Previous
Next
14.2.7 Step 7
Using the getent command, view the research group members again, but also use getent to
show the student group, and the passwd and shadow databases for the student user:
The output should now show that both sysadmin and student are secondary members of
the research group.
The GID of the student group matches the fourth field of the passwd information. This is what
makes the student a primary member of the student group.
Finally, the ! appearing in the password field (second field) of the shadow file, shows that the
password for the student has not been set.
Previous
Next
14.2.8 Step 8
Use the passwd command to set the password, netlab123 for the student user and view
the shadow file entry for the student user again:
passwd student
(type the same password twice)
getent shadow student
The output from the /etc/shadow file now shows an encrypted password in the second field:
Previous
Next
14.2.9 Step 9
Just because a user has a password doesn't mean that they have ever logged into the system.
Use the last command to see if the student has ever logged in:
last
last student
The output of the last command should show that the sysadmin user has logged in before, but
not the student user:
root@localhost:~# last
sysadmin console Mon Apr 11 19:08 still logged in
sysadmin console Mon Apr 11 19:08 - 19:08 (00:00)
wtmp begins Mon Apr 11 18:25:26 2016
root@localhost:~# last student
wtmp begins Mon Apr 11 18:25:26 2016
root@localhost:~#
There is also a lastb command, which works similar to the last command except that it shows
"bad" or failed log in attempts.
If you no longer wanted the student user to have access to the system, then the usermod -L
student command could be used to "lock" the account. The account could be unlocked with
the usermod -U student command.
A more permanent solution to preventing access to the student account would be to delete the
account with either the userdel student or userdel -r student commands. Using the -
r option with the userdel command removes the user's home directory and mail, in addition to
deleting the user's account.
Previous
Next
14.2.10 Step 10
Delete the student account and remove the user's home directory:
userdel -r student
Previous
Next
15.1 Introduction
This is Lab 15: Ownerships and Permissions. By performing this lab, students will learn how to
set and view the ownerships and permissions of files and directories.
In this lab, you will perform the following tasks:
Previous
Next
Previous
Next
15.2.1 Step 1
Create two directories and two files in the /tmp directory:
cd /tmp
mkdir priv-dir pub-dir
touch priv-dir/priv-file
touch pub-dir/pub-file
sysadmin@localhost:~$ cd /tmp
sysadmin@localhost:/tmp$ mkdir priv-dir pub-dir
sysadmin@localhost:/tmp$ touch priv-dir/priv-file
sysadmin@localhost:/tmp$ touch pub-dir/pub-file
sysadmin@localhost:/tmp$
Previous
Next
15.2.2 Step 2
View the contents of the directories:
ls -l priv-dir
ls -l pub-dir
sysadmin@localhost:/tmp$ ls -l priv-dir
total 0
-rw-rw-r-- 1 sysadmin sysadmin 0 Apr 11 21:26 priv-file
sysadmin@localhost:/tmp$ ls -l pub-dir
total 0
-rw-rw-r-- 1 sysadmin sysadmin 0 Apr 11 21:27 pub-file
sysadmin@localhost:/tmp$
Notice that for each file displayed, the first character of the line is the hyphen, -. This conveys
that the items are regular files. The first character of the listing indicates the type of file,
where d indicates a directory, - is a regular file, l is a symbolic link, b is a block device file, c is
a character device file, p is a pipe file and s is a socket file.
The next nine characters are in three groups of three characters. The first group of three
characters (rw- in the example above) are the user owner's permissions, the next three
characters (rw- in the example above) are the group owner's permissions and the last three
characters (r-- in the example above) represent everyone else's permissions (referred to as
"others").
When viewing permissions, r indicates the read permission, w indicates the write permission
and x indicates executepermission. A - character indicates that that permission has not been
granted.
Following the permissions is a link count number, indicating how many files are linked to this file.
Next, you see the user owner, the group owner, the size of the file, the date/time the file was last
modified and the file name.
Previous
Next
15.2.3 Step 3
If you want to make a directory more private, then you can use the chmod command to remove
permissions that others have on the directory. Use the chmod command to remove the other's
permissions for read and execute:
ls -ld priv-dir/
chmod o-rx priv-dir/
ls -ld priv-dir/
The output now shows that others have no permission or access to the priv-dir:
You used the chmod command to modify the permissions for others by using an o character
followed by either a + character or a - character to add or subtract permissions. The = character
can be used to set an exact permission.
You can use a u character instead of an o character to modify the permissions of the user owner.
Use a g character if you want to change permissions for the group owner.
To modify everyone's permissions use an a character instead of o, u or g.
Examples:
chmod go+r file #adds read permission for group owner and others
Previous
Next
15.2.4 Step 4
If you want to make a directory more public, then you can use the chmod command to add write
permission for others:
ls -ld pub-dir/
chmod o+w pub-dir/
ls -ld pub-dir/
Your output now shows that others have write permission on the directory (the ability to add or
delete files inside the directory):
Previous
Next
15.2.5 Step 5
Use the chmod command to remove any permission from the group or others on the priv-file:
ls -l priv-dir/priv-file
chmod g-rw,o-r priv-dir/priv-file
ls -l priv-dir/priv-file
sysadmin@localhost:/tmp$ ls -l priv-dir/priv-file
-rw-rw-r-- 1 sysadmin sysadmin 0 Apr 11 21:26 priv-dir/priv-file
sysadmin@localhost:/tmp$ chmod g-rw,o-r priv-dir/priv-file
sysadmin@localhost:/tmp$ ls -l priv-dir/priv-file
-rw------- 1 sysadmin sysadmin 0 Apr 11 21:26 priv-dir/priv-file
sysadmin@localhost:/tmp$
Previous
Next
15.2.6 Step 6
Grant all users the same read and write permission of the pub-file:
ls -l pub-dir/pub-file
chmod a=rw pub-dir/pub-file
ls -l pub-dir/pub-file
sysadmin@localhost:/tmp$ ls -l pub-dir/pub-file
-rw-rw-r-- 1 sysadmin sysadmin 0 Apr 11 21:27 pub-dir/pub-file
sysadmin@localhost:/tmp$ chmod a=rw pub-dir/pub-file
sysadmin@localhost:/tmp$ ls -l pub-dir/pub-file
-rw-rw-rw- 1 sysadmin sysadmin 0 Apr 11 21:27 pub-dir/pub-file
sysadmin@localhost:/tmp$
Previous
Next
15.2.7 Step 7
Create a test.sh file in the /tmp containing the content "date":
If a file contains commands, then those commands can be run, or executed, if the file has
execute permission for the user. The process of making a file into an executable file requires
giving the execute permission on the file. Without this permission, the file can't be treated as a
program.
Previous
Next
15.2.8 Step 8
Attempt to execute the test.sh file; it should fail. View the permissions on the file to see why:
./test.sh
ls -l test.sh
sysadmin@localhost:/tmp$ ./test.sh
-bash: ./test.sh: Permission denied
sysadmin@localhost:/tmp$ ls -l test.sh
-rw-rw-r-- 1 sysadmin sysadmin 5 Apr 11 22:27 test.sh
sysadmin@localhost:/tmp$
Previous
Next
15.2.9 Step 9
Only the user owner of a file (or the root user) is allowed to change permissions on a file. Give
yourself, the user owner, execute permission and then execute test.sh:
The output shows the added execute permission for the user owner and the current date and time
from executing the datecommand inside of your test.sh script file:
So far, you have seen how to use the chmod command with symbolic notation, where symbols are
used to represent who (u, g, o, and a), how (+, -, or =), and what to change (r, w, and x).
The chmod command can also be used with a numeric value representing the permissions of the
user owner, group owner and others in what is called octal notation.
To use the chmod command with octal notation, you must first understand the octal value of the
permissions:
Read (r) 4
Write (w) 2
Execute (x) 1
From the last listing of the test.sh file, the permissions were shown to be rwx for the user
owner, rw for the group owner, and r for others. To express these permissions in octal notation,
a total is calculated for each ownership.
As a result the user's permission total would be calculated as 4 + 2 + 1, or 7, where 4 is for the
read, 2 is for the write and 1 is for the execute permission.
The group's permission total would be 4 + 2 or 6, where 4 is for the read permission, and 2 is for
the write permission.
The others' ownership permission would simply be 4 for the read permission that they have.
Putting it all together the octal value for the current permissions would be 764.
Previous
Next
15.2.10 Step 10
Use the stat command to verify that the octal value for the permissions (access) to
the test.sh:
stat test.sh
sysadmin@localhost:/tmp$ stat test.sh
File: `test.sh'
Size: 5 Blocks: 8 IO Block: 4096 regular file
Device: fc00h/64512d Inode: 3540004 Links: 1
Access: (0764/-rwxrw-r--) Uid: ( 1001/sysadmin) Gid: ( 1001/sysadmin)
Access: 2016-04-11 22:27:24.987740243 +0000
Modify: 2016-04-11 22:27:24.987740243 +0000
Change: 2016-04-11 22:35:08.335757863 +0000
Birth: -
sysadmin@localhost:/tmp$
If you wanted to change these permissions using octal notation to give the group and others
execute permission, then you would use the following three numbers:
The new mode, or octal number, for the permissions would then be 775.
Previous
Next
15.2.11 Step 11
Using octal notation, modify the permissions of the test.sh file, so everyone would be able to
execute the file:
There are two commands that can affect the ownership of files. The chown command can only be
executed by the root user and it can change the user that owns a file or both the user and group
that owns a file.
The chgrp command can be used by either the user who owns a file or by the root user.
The chgrp command only changes the group that owns a file.
When a non-root user uses the chgrp command they can only change the group ownership to a
group of which they are a member. The root user can use chgrp to change the group ownership
of any file to any group.
Previous
Next
15.2.12 Step 12
Switch to the root user so you will be able to execute both the chown and chgrp commands to
change group ownerships to any group:
su -
(provide the root password: netlab123)
sysadmin@localhost:/tmp$ su -
Password:
root@localhost:~#
Previous
Next
15.2.13 Step 13
Change to the /tmp directory and list the details of the pub-dir, and then its contents:
cd /tmp
ls -ld pub-dir
ls -l pub-dir/pub-file
Notice the output shows the directory and the file owned by the sysadmin user, and
the sysadmin group:
root@localhost:~# cd /tmp
root@localhost:/tmp# ls -ld pub-dir/
drwxrwxrwx 2 sysadmin sysadmin 4096 Apr 11 22:48 pub-dir/
root@localhost:/tmp# ls -l pub-dir/pub-file
-rw-rw-rw- 1 sysadmin sysadmin 0 Apr 11 22:48 pub-dir/pub-file
root@localhost:/tmp#
Previous
Next
15.2.14 Step 14
Use the chown command to change the user and group owner of the pub-dir to the root user
and the root group. Then view the details of the directory:
Your output should show both the user and group owners have changed:
Previous
Next
15.2.15 Step 15
Use the chown command to change the user owner of the pub-file to the bin user:
The output now shows that the user owner has been updated to bin:
Previous
Next
15.2.16 Step 16
View the details of the priv-dir and its contents:
ls -ld priv-dir
ls -l priv-dir/priv-file
The output should show that priv-dir is owned by the sysadmin user and sysadmin group:
Previous
Next
15.2.17 Step 17
Change the group owner of the priv-dir and priv-file to the users group recursively with
the chgrp command and view the updated files:
ls -ld priv-dir
ls -l priv-dir/priv-file
chgrp -R users priv-dir
ls -ld priv-dir
ls -l priv-dir/priv-file
root@localhost:/tmp# ls -ld priv-dir
drwxrwx--- 2 sysadmin sysadmin 4096 Apr 11 22:48 priv-dir
root@localhost:/tmp# ls -l priv-dir/priv-file
-rw------- 1 sysadmin sysadmin 0 Apr 11 22:48 priv-dir/priv-file
root@localhost:/tmp# chgrp -R users priv-dir
root@localhost:/tmp# ls -ld priv-dir
drwxrwx--- 2 sysadmin users 4096 Apr 11 22:48 priv-dir
root@localhost:/tmp# ls -l priv-dir/priv-file
-rw------- 1 sysadmin users 0 Apr 11 22:48 priv-dir/priv-file
root@localhost:/tmp#
Your output reflects that when applying changes recursively to a directory, that the changes apply
to the directory and anything it contains. This would mean that every sub directory under priv-
dir and every file in priv-dir and all of its subdirectories would have this change applied.
Previous
Next
16.1 Introduction
This is Lab 16: Special Permissions. By performing this lab, students will learn about special
permissions and different kinds of link files.
In this lab, you will perform the following tasks:
Previous
Next
16.2 Viewing Special Permissions
In this task, you will find and understand the purpose of special permissions beyond read, write,
and execute.
Previous
Next
16.2.1 Step 1
List the details of the /tmp and /var/tmp directories:
ls -ld /tmp
ls -ld /var/tmp
The /tmp and /var/tmp directories are read, write and executable for everyone. Besides the
users' home directories, these two "temporary" directories are the locations in the filesystem
where ordinary users can create new files or directories.
This does pose a problem: if all users can create new files, they are also able to delete existing
files. This is because the write permission on a directory grants users the ability to add and delete
files in a directory.
The t in the execute column for the others permissions indicates that this directory has the sticky
bit permission set. This special permission means that even though everyone can add files in
these directories, only the user who creates a file can delete that file.
The root user is not affected by this permission as that account can delete all files in the directory,
regardless of ownership.
Previous
Next
16.2.2 Step 2
View the permissions on the /etc/shadow file:
ls -l /etc/shadow
The output shows that the root user has read and write permissions, members of the shadow
group have read permission, and others have no permission on this file:
sysadmin@localhost:~$ ls -l /etc/shadow
-rw-r----- 1 root shadow 838 Mar 14 17:34 /etc/shadow
sysadmin@localhost:~$
Like the other files found in the /etc directory, the /etc/shadow file contains host-specific
configuration information. Specifically, the /etc/shadow file contains the encrypted passwords
of all local user accounts and information about password aging (how long a password is good).
Since this is very sensitive information, access to this file is limited to the root user and
commands executing as root, as well as members of the shadow group.
When a user updates their password with the passwd command, the passwd command executes
with a special permission called setuid. The setuid permission causes a file to execute as the
user that owns the file, instead of the user that is actually running the command.
If you are coming from a Microsoft Windows background, you can think of setuid to be like the
"Run as administrator" feature provided in Windows.
Previous
Next
16.2.3 Step 3
View the permissions of the /usr/bin/passwd file:
ls -l /usr/bin/passwd
sysadmin@localhost:~$ ls -l /usr/bin/passwd
-rwsr-xr-x 5 root root 42824 Sep 12 2012 /usr/bin/passwd
sysadmin@localhost:~$
Notice the s in the user's execute permission column. This indicates that this file has the setuid
permission set, so it executes as the user who owns it (root) instead of the user running the
command.
Thus, the passwd command is able to update the /etc/shadow file, as it executes as
the root user (recall that the root user can edit any file, regardless of the permissions on the file).
Previous
Next
16.2.4 Step 4
View the permissions on the /usr/bin/wall command:
ls -l /usr/bin/wall
The output now shows the s in the execute column for the group:
sysadmin@localhost:~$ ls -l /usr/bin/wall
-rwxr-sr-x 5 root tty 18976 Jun 18 2014 /usr/bin/wall
sysadmin@localhost:~$
The s in the group execute column indicates that this file has the setgid permission set, so it
executes as the group who owns it (tty) instead of the group of the user running the command.
Thus, the wall command is able to write to all terminals (ttys) as it executes as the tty group.
Note: This is very similar to the setuid permission, but instead of running the command as the
user owner of the program, the command runs as the group owner of the program.
So far, you've seen three types of special permissions: sticky bit on a directory, setuid on an
executable file and setgid on an executable file. As you have seen, these three types exist on a
typical system.
One more special permission type can be used; The setgid permission can also be applied to a
directory.
If you see the s in the execute column for the group that owns directory, then the directory has
the setgid permission. When a directory has the setgid permission, then any new file or directory
created in that directory will automatically be owned by the group that owns the directory, not by
the group of the user who created the file.
Previous
Next
Previous
Next
16.3.1 Step 1
Change to your home directory:
cd
Previous
Next
16.3.2 Step 2
Create a file named source containing the text "data" by using redirection:
Previous
Next
16.3.3 Step 3
View the details and inode information of the source file:
ls -li source
The highlighted output shows that the file has an inode number of 2076 (this number will vary
from one system to another) and a link count of 1:
The Linux operating system uses inodes to keep track of the information about a file. A directory
entry associates an inode with a file name.
Creating a hard link creates another directory entry associated with an existing inode, and will
increase the link count number.
Hard links allow you to have multiple names to refer to the same file. If any one of these names is
removed, then the other names can still be used to refer to the file.
In fact, these other names can even be used to create additional links. All of these names are
considered equivalent as they all refer to an existing inode.
Note: You cannot create hard links to directories. Also, a hard link to a file also must exist within
the same filesystem (partition) as the file that it links to.
Previous
Next
16.3.4 Step 4
Use the ln command to create a hard link. View the details and inode information of the source
and new hard link file:
ln source hardlink
ls -li source hardlink
Notice that the hardlink file and the original source file share the same inode:
Previous
Next
16.3.5 Step 5
Use the ln command to create another hard link to the source file. View the details and inode
information of the source and new hard link files:
ln hardlink hardtoo
ls -li hardlink hardtoo source
Notice the output continues to show the hardlinks share the same inode and the link count
increases on all links when a link is added:
Previous
Next
16.3.6 Step 6
Remove the last link that was created and list the source and hardlink files:
rm hardtoo
ls -li source hardlink
Notice that the link count decreases when one of the hard linked files is removed:
sysadmin@localhost:~$ rm hardtoo
sysadmin@localhost:~$ ls -li source hardlink
2076 -rw-rw-r-- 2 sysadmin sysadmin 5 Apr 12 13:27 hardlink
2076 -rw-rw-r-- 2 sysadmin sysadmin 5 Apr 12 13:27 source
sysadmin@localhost:~$
Previous
Next
16.3.7 Step 7
Remove the hardlink file and list the source file details:
rm hardlink
ls -li source
sysadmin@localhost:~$ rm hardlink
sysadmin@localhost:~$ ls -li source
2076 -rw-rw-r-- 1 sysadmin sysadmin 5 Apr 12 13:27 source
sysadmin@localhost:~$
Another type of link that can be created is known as a symbolic link or soft link. Symbolic links do
not increase the link count of files with which they are linked.
Symbolic link files have their own inode and type of file. Instead of linking and sharing an inode,
they link to the file name. Unlike hard links, soft links can be linked to directories and can cross
devices and partitions to their targets.
Previous
Next
16.3.8 Step 8
Create a symbolic link to the source file and view the details of both files:
ln -s source softlink
ls -li source softlink
The highlighted output shows that the softlink and the source file have different inodes.
Notice that the link type of file is created when making a symbolic link. The permissions of the link
are irrelevant, as it is the permissions of the target file that determine access:
Next
16.3.9 Step 9
Create a symbolic link to the /proc directory and display the link:
ln -s /proc crossdir
ls -l crossdir
The success of these commands shows that soft links can refer to directories, and they can cross
from one filesystem to another, which are two things that hard links cannot do:
Previous
Next