Beruflich Dokumente
Kultur Dokumente
Foreword
The intended purpose of this document is to have a place to store my own thoughts and
notes while I study for the Linux+ LX0-103 test. These notes will be fragmented, and may
not make any direct sense to anyone but me.
CompTIA Linux+ Powered by Linux Professional Institute Study Guide: Exam LX0-103 and
Exam LX0-104 3rd Edition
by Christine Bresnahan and Richard Blum
Command Line
Exam Objectives
Shells
A shell is a program that accepts and interprets text-mode commands and provides an
interface to the system.
The most commonly used shell is bash (GNU Bourne Again Shell), and it is most
emphasized on the exam.
Default interactive shell The shell program a user uses to enter commands, run
programs/scripts, etc.
Default system shell Used by the Linux system to run system shell scripts (typically at
start-up).
The /bin/sh file is a pointer to the systems default system shell, which is normally
/bin/bash for Linux.
To access a shell you can either log into Linux via text-mode, or load a GUI such as
terminal, xterm, konsole, etc. Either option will bring you to the default interactive shell.
To use a shell you simply type a command, possibly add options and/or a path to it, and
then the computer executes the command.
Most commands are external but some commands are internal (built-in) to the shell itself.
Command Description
cd Changes directories
To determine if a command is internal or not, you can use the type command:
$ type <command>
$ type type
type is a shell builtin
Some commands also have a duplicate external command in addition to the internal
command of the same name. To check for duplicates:
$ type -a <command>
$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd
Internal commands take precedence over external commands when both are present. In
order to access an external command you must provide the complete external command
path (ex. /usr/bin/time rather than time).
When a command is ran the shell checks for an internal command first. If none is found, it
will check for external command within any of the directories listed
in the $PATH environment variable.
If a command is not internal or present on the $PATH, it can be run by providing a full path
name on the command line.
In order for any file to be ran it must have the executablebit marked on its file permissions
(ex. -rwxr--r--).
BASH Navigation
The tilde (~) character can be used as a shortcut to represent the current users home
directory path (ex. ~translates to /home/jeff when logged in as the user named jeff).
When an interactive shell that is not a login shell is started, bash reads and executes
commands from a ~/.bashrcfile, if it exists.
When a login shell exists, bash processes any commands from files
at ~/.bash_logout and /etc/bash.bash_logout, if those files exist.
Pressing the tab key will cause the shell to try to fill out the rest of the command or
filename. If there are multiple possible matches, it will display them when you press
the tab key a second time. This is called command completion, which is supported in
bash and tcsh.
The bash shell provides many hotkeys for navigation, based on the Emacs editor:
Hotkey Details
History
The shell keeps a log of every command you type, called history. To access this history:
$ history
Hotkey Details
^P / ^N Same as Up / Down.
Esc < Go to first item in history.
^G Terminate search.
The bash history file is stored at ~/.bash_history (i.e. within your users home directory).
The bash history does not store what you type in response to other prompts made by
commands or programs. Because of this, it is advisable to not enter sensitive information
(passwords, SSNs, etc.) as an argument to a command, but rather enter it when prompted
by the command being run.
Environment Variables
These variables (and their data) are available to all programs, including the shell itself.
Getting Help
Command Description
By default, man uses the less pager to display the manual pages.
Most Linux distributions provide a whatis database, which contains short descriptions of
each man page and keywords for searches.
Man pages can be broken down into several sections based on number:
5 File formats
6 Games
9 Kernel routines
Man generally returns the lowest-numbered section, but you can force it to display a
particular section number with:
$ man <section_num> <command>
Hotkey Description
q Quit
Linux treats input and output from programs as a stream which is a data entity that can
be manipulated.
Input and output streams can be redirected from or to other sources, including files.
Similarly, output from one program can be piped to another program as its input.
File Descriptors
Linux handles all objects as files including a programs input and output stream.
Redirects
Input and output can be redirected by using specific operators following a command and its
options:
Operator Effect
&> (bash) Creates a new file containing both standard output and standard error.
2>&1 (ksh, csh) File overwritten if exists.
> file 2>&1 (dash)
<> Causes the specified file to be used for both standard input and
standard output.
Pipes
Data pipes (a.k.a. pipelines) can be used to send STDOUT from one program to the STDIN of
another program:
$ first_program | second_program
Tee
The tee command is often used with pipes to split STDOUT so that its both displayed
on screen and sent to a file:
$ echo $PATH | tee path.txt
/usr/lib64/qt-3.3/bin:/usr/local/bin:[...]
Note: tee will overwrite files unless you pass the -a option to it.
Generating Commands
The xargs command passes its STDIN as the STDIN to whichever command you wish:
$ xargs [options] [command [initial-arguments]]
By default, xargs delimits its input by spaces and newlines. To force a particular character
to use for delimiting, use the -d option:
$ find / -user jeff | xargs -d "\n" rm
Since backticks can sometimes not work very well in complex situations, enclosing
commands with a $() is generally preferred:
$ rm $(find ./ -user jeff)
Text Filters
The cat, join, and paste commands all join files end-to-end based on fields within the file,
or by merging on a line-by-line basis.
Cat / Tac
The cat command is short for the word concatenate. It combines the contents of files
together and sends the data to STDOUT:
$ cat first.txt second.txt > combined.txt
It can also be used to display the contents of a file to the screen when using cat without a
redirect:
$ cat hello_world.txt
hello world!
Option Description
tac is the same as cat, but it reverses the order of lines in the output.
Join
The join command combines two files by matching their contents on a delimited field
specified by the user:
$ join file1.txt file2.txt
006 Trevelyan, Alec deceased
007 Bond, James active
By default, join uses a space character as the field delimiter. However, the delimiter can
be changed with the -t option:
$ join -t , file1.txt file2.txt
The join command also defaults to using the first delimited field for matching. This can be
changed by using an option corresponding to the file number (ex. -1, -2, -3, , -99)
followed by the field number to use:
$ join -1 3 -2 2 file1.txt file2.txt
Paste
The paste command merges files line-by-line, separating the lines from each file with tabs:
$ paste file1.txt file2.txt
file1_line1 file2_line1
file1_line2 file2_line2
Commands for transforming the contents of files doesnt actually change their content, but
you can redirect their STDOUT to a new file or pipe it to another command.
Sort
By default, the sort command will sort files by the first field using case-sensitive ASCII
values.
Option Description
-n Sort by number.
--numeric-sort
Split
The split command can split a file into two or more files, which receive an automatically
generated alphabetic suffix.
By default, split will create output files in 1,000-line chunks, with names ending
in aa, ab, ac, etc.
Option Description
Translate Characters
Shortcut Description
Option Description
The expand command converts tab characters into spaces. Each tab becomes 8 spaces by
default, but this can be changed with the -t or --tabs= options.
The unexpand command converts multiple spaces into tab characters. Just
like expand, unexpand can use the -t or --tabs= options to specify the number of characters
per tab.
The od (octal dump) command can be used to display a file in an unambiguous byte data
format, such as:
octal (base 8), hexadecimal (base 16), decimal (base 10), and even ASCII with escaped
control characters.
The first field on each line is an index of the file in octal. The second line begins at octal 20
(16 in decimal) bytes into the file. The remaining numbers represent the bytes in the file.
File Formatting
The fmt, nl, and pr commands are used to reformat text within a file.
Fmt
fmt can be used to clean up files with long line lengths, irregular line lengths, or other
problems.
The width of formatted paragraphs can be changed with the -<width>, -w <width>, and -
-width=<width> options.
NL
By default, nl starts each new page on line 1. The -p or --no-renumber option will prevent
the line number reset on each page.
ln Left justified
rn Right justified
The header, body, and footer of a page can be styled with -h <style>, -b <style>, and -f
<style>.
Alternatively --header-numbering=<style>, --body-numbering=<style>, and --footer-
numbering=<style>:
pREGEXP Only lines that match the regular expression (REGEXP) are
numbered.
pr can be used to prepare a plain-text file for printing by adding headers, footers, page
breaks, etc.
The pr command itself does not handle printing, but its output is often piped to
the lpr command to actually handle printing.
By default, pr assumes an 80-character line length with a monospaced font; and outputs
the original text with headers that include the current date, time, filename, and page
number.
Option Description
-F Creates a form-feed character between pages, rather than just using a fixed
-f number of blank lines (default).
--form-feed
Note: The pr command was built around assumptions for printer capabilities back in the
80s. The command can still be useful today, but GNU
Enscript(http://www.codento.com/people/mtr/genscript/) is preferred. This program has
many of the same features as pr, but it generates PostScript output that can take better
advantage of modern printers and their features.
File Viewing
Head
If more than one file is passed to head, it will precede each files output with a header to
identify it.
Option Description
Tail
Option Description
Note: head and tail can be combined to display or extract portions of a file. For example, if
you want to display lines 11 15 of a file named sample.txt, you could extract the first 15
lines with head and display the last five of those with tail:
$ head -n 15 sample.txt | tail -n 5
Less / More
Hotkey Description
q Quit
File Summarizing
Cut
Option Description
<list> can be a single number (ex. 4), a closed range of numbers (ex. 2-4), or an open
range of numbers (ex. -4 or 4-).
WC
The above output shows that file.txt contains 308 lines (308 newline
characters), 2343 words, and 15534 bytes.
Option Description
Note: Character and byte counts are typically identical on most ASCII files, unless multibyte
character encoding is used.
Regular Expressions
Regular Expressions (RegEx) are tools for describing or matching patterns in text:
Grep
grep searches for files that contain a specific string, returning the name of the file and a line
of context for the match (if the file is a text file):
$ grep [options] <regexp> [files]
Option Description
The above command will recursively search for the pattern eth0 within all files of all
directories inside of /etc, and any file found to match that string will be printed to STDOUT.
To find all files that contain a match for eth0 and eth1, the above command can be rewritten
as:
$ grep -r eth[01] /etc/*
The above command will search all files within the /etcdirectory for anything
containing alchemist.digital or mr2.run with the number 169 on the same line.
Note: Sometimes shell quoting is necessary to ensure grep has a chance to use certain
characters in a regular expression before the shell attempts to parse them for its own
purpose (ex. |, *, etc.)
Sed
sed directly modifies a files contents and sends the changes to STDOUT.
The contents of <script-file> or <script-text> are a set of commands that sed will
perform.
By default, commands operate on the entire file. However, an address (line number) can
be provided to ensure the command only operates on the desired lines.
Unix (and Linux) use a single line feed character (ASCII 0x0a, sometimes represented
as \n) as the end of a line in a file.
DOS and Windows use the combination of a carriage return (ASCII 0x0d or \r) and a line
feed (i.e. \r\n).
To convert files from one system to another there is special-purpose programs such
as dos2unix and unix2dos:
$ dos2unix file.txt
Alternatives
Since not all distributions have these utilities, an alternative to convert from DOS to
Unix would be:
$ tr -d [[backslash backslash]]r < dosfile.txt > unixfile.txt
The above tr command is run with the -d (delete) option to remove all carriage returns (\r)
using the escaped literal backslash in the set. The tr commands input is
the dosfile.txt file, and the output is redirected to the unixfile.txt file.
The above command uses the regexp of $ for the end of line, and replaces it with
a \r (carriage return) in its place. The input for the command is the unixfile.txt and the
redirected output goes into the dosfile.txt.
Note: Another option is to have a text editor save the file using a different file-type setting,
but not all editors support this feature/option.
Command-line editing lets you edit a retrieved command or change a typo before
submitting the command.
The information provided is a succinct summary thats useful for reference or to learn
about exact command options and/or features.
This information can be read by programs and used to modify program behavior in a way
thats appropriate for the current environment.
They can be used to link together a series a simple programs in order to perform more
complex tasks than they could do individually.
These commands accomplish tasks such as: combining files, transforming the data in files,
formatting text, displaying text, and summarizing data.
They can contain normal alphanumeric characters, which match the exact same
characters in the string they are describing. They can also contain several special symbols
and symbol sets that match multiple different characters.
Overall, regular expressions are a powerful pattern-matching tool used by many Linux
programs.
How to check environment variables (hint: env, echo $<name>), how to set environment
variables (hint: export <name>=<value>, or <name>=<value> -> export <name>), how to
delete environment variables (hint: unset <name>), and the common environment variables
(hint: $TERM, etc).
The difference between the default interactive shell and the default system shell (hint: /bin/sh
points to the system shell).
The difference between internal and external commands, which one takes precedence if both
exist (hint: internal), how to determine if a command is internal / built-in (hint: builtin
command) or external (hint: type command), and how to tell if both internal and external
commands exist (hint: type -a) .
What xterm, terminal, and konsole are and how they differ.
What the systems path is (hint: $PATH), how it stores its values (hint: colon-delimited list of
directories), how to check its values, how to set its values, and how to run commands not on
the path (hint: ./<program_name> or /<full_path>/<program_name>).
Which permission / bit needs to be set in order to run a program / script (hint: executable bit),
and how to change permissions (hint: chmod).
The shell shortcuts like command completion (tab complete) and history.
Ctrl+X -> Backspace to delete all text from the cursor to start of line.
Ctrl+T to transpose (swap) the character under the cursor with the one before it.
Esc -> T to transpose the two words before / under the cursor.
Esc -> U for UPPERCASE, Esc -> L for lowercase, and Esc -> C for Capitalize Case.
Ctrl+X -> Ctrl+E to open a full editor (defined in $FCEDIT or $EDITOR, defaults to Emacs).
Where the bash configuration files are (hint: ~/.bashrc and /etc/profile) and how to set them.
How to find help documents and information on commands and options (hint: man, info, and
help), how to search based on keyword (hint: man -k <keywords>), how to establish a
keyword database (hint: the whatis database and the makewhatis command), and how to
change the pager that displays the information (hint: man -P <path_to_pager> <command>).
5 File formats.
6 Games.
9 Kernel routines.
Q to quit.
How Linux treats all objects (hint: as files), what file descriptors are available (hint: 0, 1, 2),
how to redirect input (STDIN) / output (STDOUT) / error (STDERR) streams (hint: >, >>, 2>,
2>>, &>, <, <<, <>), how to use a here document / heredoc (hint: command <<
eof_marker), and how to discard STDERR messages (hint: 2> /dev/null).
How to use pipes to redirect and chain pipelines from multiple programs together (hint: prog1
| prog2).
How to send STDOUT to both the screen and to another file or program (hint: tee).
How to build new commands programmatically (hint: xargs), and what other options are
available (hint: `backticks` and $() enclosures ).
How to combine files (hint: cat), join files on a common field (hint: join), merge lines together
(hint: paste), sort the content of files (hint: sort), delete duplicate lines (hint: uniq), and split
files into multiple files (hint: split).
How to convert between tabs and spaces (hint: expand, unexpand), convert a file to octal /
hexadecimal / escaped ASCII (hint: od), and change characters in a file (hint: tr).
How to format a file (hint: fmt), add line numbers (hint: nl, cat -b), how to prepare for printing
(hint: pr), and how to print (hint: lpr).
How to quickly view files without opening them in an editor (hint: head, tail).
Subexpressions .*(\.digital)?
How to replace the contents of a file directly from the command line (hint: sed).
Commands to know:
uname
cd
rm
pwd
echo
time
set
exit
logout
type
builtin
chmod
env
export
unset
man
info
less
more
find
tee
xargs
cat / tac
join
paste
sort
tr
expand / unexpand
grep
sed
head
tail
cut
wc
man 7 regex
ps