Upload
binsent-ribera
View
2.183
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Linux 1 Hand-Outs
Citation preview
IBM System Programming TrainingModule 2 - Linux Basics
1
Unit 1 – Introduction to Linux
A Short History of Linux
1984: Richard Stallman starts GNU project GNU's Not UNIX http://www.gnu.org
Purpose: Free UNIX "Free as in Free Speech, not Free Beer"
First step: re-implementation of UNIX Utilities C compiler, C library emacs bash
To fund the GNU project, the Free Software Foundation is founded http://www.fsf.org
1991: Linus Torvalds writes 1st version of Linux kernel Initially a research project about the 386 protected mode Linus' UNIX -> Linux Combined with the GNU and other tools forms a complete UNIX system
1992: First distributions emerge Linux kernel GNU and other tools Installation procedure
What's So Special About Linux?
Most software (including the Linux kernel) is GPL'ed (GNU General Public License) http://www.gnu.org/copyleft/gpl.html
Is called "copyleft" (instead of "copyright") You may copy the software You get the source code You may alter the source code and recompile it You may distribute the altered source and binaries You may charge money for all this
You only may not change the license So all your customers have the same rights as you So you really cannot make money from selling the software alone
Other Open Source licenses (e.g. BSD) are also used
Effects of the License Model
Everybody has access to the source Volunteer software development on the Internet, with central
coordination Linus Torvalds coordinates kernel development Others coordinate other pieces of the OS
Peer reviews possible Security Performance
License cannot change So your changes (and name) will stay in forever
Linux has become a Way of Life
Culture
Celebrities Linus Torvalds Richard Stallman Eric Raymond
Humor User-friendly Segfault
Mascot Tux
Linux Today
Linux covers the whole spectrum of computing Embedded devices Laptops Desktop systems Development systems Small and large servers Megaclusters/supercomputers
Linux is used throughout the world and in space
Linux is used by home users and by some of the largest companies in the world IBM Boeing NASA
Unit 2 - Installing Linux
Preparing a System for Installation
Know your hardware CPU, memory, keyboard, mouse Hard disks, CD-ROM players Graphical adapters, monitor capabilities Network adapters, IP addresses Printers
Is all your hardware supported? Linux Hardware-HOWTO Distributors Hardware Compatibility List Hardware manufacturer
2
If unsure, just try it!
Make space for Linux partitions
Know your Hardware
Obtain information from Manuals Windows Control Panel
Partitioning Theory
Partitioning is necessary on Intel-based computers Maximum of four primary partitions One primary partition may be an extended partition An extended partition can hold an unlimited amount of logical
partitions (but the OS may pose a limit anyway)
Partitioning Tools
PartitionMagic Commercial program from PowerQuest Runs under MS-DOS and Windows Can create/resize/move/delete partitions
GNU parted Can create/resize/move/delete partitions QTParted is a graphical frontend for parted
fdisk Virtually every PC OS (Windows, OS/2, Linux) comeswith a tool
"fdisk" to create partitions for that OS
Disk Druid, YaST and others Partitioning programs integrated in install program
Installing Linux
Boot system from bootable media All modern PCs can boot from CD-ROM directly
o Must be enabled in BIOS Otherwise boot from floppy
Some distributions require additional disks All disk images are usually stored on the CD-ROM
After booting, install from: Local CD-ROM/DVD Local Hard Disk Network
Installation Steps
All installation programs need to perform essentially the same steps:1. Choose language, keyboard type, mouse type2. Create partitions3. Set up a boot loader4. Configure network5. Configure users and authentication6. Select package groups7. Configure X8. Install Packages9. Create Boot Disk
Order of steps may vary from distribution to distribution
Other steps may also be included e.g. firewall, printers, sound
Select Language, Keyboard, Mouse
Select the language to be used during installation process Different distributions support different languages
Select the keyboard layout Different countries use different keyboard layouts Dead (compose) keys allow you to input accented or special
characters such as é, ç, ß and so forth.
Select your mouse A mouse can be connected using a PS/2, USB or serial
connector If your mouse has only 2 buttons, you can emulate the third
(middle) button by clicking both buttons simultaneously
Install Class
Most distributions have default installation "classes" for typical users Workstation Laptop Server
A "custom" class allows you to make all decisions yourself
3
Packages to be installed Various configuration options
Disk Partitioning
Linux installation requires you to create Linux partitions At a minimum, create: / (root) – 750MB; /swap – 64 – 256MB Recommended: /boot – 16MB May need/want to create other partitions: /usr, /usr/local, /var, /tmp,
/opt, and /home
Configure a Boot Loader
Boot Loader loads and starts the Linux kernel Can boot other operating systems as well OS/2, Windows, BeOS, Give each OS a unique label!
Can be password protected Prevents users from passing boot parameters to Linux or booting
any OS
Should generally be configured in the MBR, unless another boot loader is used
Common Boot Loaders: LILO: Linux Loader – text-based installation GRUB: GRand Unified Boot loader – GUI installation
Configure Network
Most distributions configure your network adapter as part of the installation process Ethernet Token Ring
Need the following information: IP address Subnet mask Network address Broadcast address Hostname Default router/gateway DNS server addresses
May also be configured to use DHCP
Configure Root and User Accounts
root is the superuser of the system Can do anything Needs a strong password Do not use your system as root unless you need to!
Most distributions allow you to add user accounts during installation too:
Create a user account for every individual user that is going to use the system
Hint: You should enable shadow passwords and MD5 encryption if available for additional security.
Select Package Groups
Most distributions have grouped individual packages in package groups
Only select the package groups you need on your workstation Selecting individual software packages is usually still possible but
tedious A typical distribution has over 1000 packages...
Configure X
X (X Window System) is the graphical user interface of Linux Needs to be configured for your system
Graphical adapter Monitor
Most adapters and monitors can be auto detected If not auto detected, select manually or use a "Generic" adapter
or monitor
Usually customization allowed: Resolution Refresh rate Color Depth
Test settings if possible If nothing works, skip X configuration
Other (Optional) Installation Screens
Some distributions offer additional installation screens: Printer configuration Firewall configuration Sound card configuration Modem configuration Time Zone configuration
Usually straightforward
Installing Packages
Installing packages may take 5 mins to several hours Most distributions provide a progress bar and/or total time
indication Some distributions provide some entertainment while installing
While installation is going on, various virtual terminals provide information on the progress Switch between Virtual Terminals using Ctrl-Alt-F1 to F6 (console
based) and Ctrl-Alt-F7 (GUI)
4
Feed additional CD's when asked for
Create Boot Disk
After installation, most distributions allow you to create a custom boot disk
Used to boot the system in case of LILO/GRUB/kernel problems System specific to some degree
Post-install Configuration
After installation has finished, your system will reboot to activate the newly installed kernel SUSE will perform the reboot during installation
For almost all Linux distributions, this is the only reboot that is ever required
After reboot, some post-installation configuration may happen Configure graphics Configure sound card Install documentation, updates, drivers Create user accounts Registration
Unit 3 - Using the System
Linux is Multi-user and Multitasking
Linux is a multi-user, multitasking operating system Multiple users can run multiple tasks simultaneously,
independent of each other
Always need to "log in" before using the system Identify yourself with username and password
Multiple ways to log in to the system Console: Directly attached keyboard, mouse, monitor Serial terminal Network connection
Virtual Terminals
In most Linux distributions, the console emulates a number of virtual terminals
Each virtual terminal can be seen as a separate, directly attached console Different users can use different virtual terminals
Typical setup: VT 1 through 6: text mode logins VT 7: graphical mode login prompt (if enabled)
Switch between VTs with Alt-Fn (or Ctrl-Alt-Fn if in X)
Linux Commands
Everything on a Linux system can be done by typing commands(Even browsing the World Wide Web...)
The Graphical User Interface (X Window System or X) is not needed for running a Linux system But is sometimes more convenient
In order to be able to type commands in X, you need to start a terminal emulator
Command Prompt
Command prompt indicates that the system is ready to accept commands
Can be configured yourself (will be covered later) Default depends on distribution
Examples:
[user@host dir]$dir$$#
dollar ($) usually means: "logged in as regular user" hash (#) usually means: "logged in as root"
Linux Command Syntax
Linux commands have the following format: $ command option/s argument/s
Examples:
$ ls$ ls -l$ ls /dev$ ls -l /dev
Command Format Examples
RIGHT WRONG
1. Separation
$ mail -f personal $ mail - f personal$ who –u $ who-u
2. Order
$ mail -s test root $ mail test root -s$ who –u $ -u who
3. Multiple options
$ who -m –u $ who -m-u$ who –mu $ who -m u
5
Some Basic Linux Commands
passwd - Change your password mkpasswd - Generate a random password date, cal - Find out today's date and displays a calendar who, finger - Find out who else is active on the system clear - Clear the screen echo - Write a message to your own screen write - Write a message to other screens wall - Write a message to all screens talk - Talk to other users on the system mesg - Switch on/off reception of write, wall and talk messages
Changing your Password
passwd command allows you to change your password
$ passwdChanging password for tux1Old password:New password:Retype new password:
Passwords are important for security - choose a good password Minimum six characters Not a dictionary word, birth date, license plate, ...
mkpasswd command generates a random password
The date Command
date shows the current date and time
$ dateFri Jun 6 11:15:10 CET 2003
The cal Command
cal shows a calendar Syntax: cal [Month] [Year]
$ cal 6 2003June 2003
Su Mo Tu We Th Fr Sa1 2 3 4 5 6 78 9 10 11 12 13 1415 16 17 18 19 20 2122 23 24 25 26 27 2829 30
Who is on the System?
who shows who is logged onto the system
$ whoroot tty1 Mar 5 11:10tux1 tty2 Mar 5 11:04
$ who am i
host!tux1 tty2 Mar 5 11:04
$ whoamitux1
Finding Information about Users
finger command shows info about other users Syntax: finger [user][@host]
$ fingerLogin Name Tty Idle Login Timetux1 Tux (1) 2 Mar 5 11:04root root *1 7 Mar 5 11:10
$ finger tux1Login: tux1 Name: Tux (1)Directory: /home/tux1 Shell: /bin/bashOn since Fri Mar 5 11:04 (CET) on tty2No mail.No plan.
The clear , echo , write and wall Commands
clear command clears your screen
$ clear
echo command writes messages to your own screen
$ echo Who wants to go to lunch?Who wants to go to lunch?
write use to display a text message on a user's terminal
$ write tux2Message<ctrl-d> # terminate
wall use to place a message on all logged in user's displays
$ wallI'm back<ctrl-d> # terminate
Talk with Another User
If John wants to talk with Fred, John enters:
$ talk fred
If Fred also wants to talk with John, Fred enters:
$ talk john
6
The mesg Command
mesg command controls whether other users can send messages to you with the write, wall or talk command or through output redirection.
User tux1 at tty1:
$ mesg nUser tux2 at tty2:
$ write tux1 tty1write: tux1 has disabled messages on tty1
Keyboard Tips
<backspace> or <ctrl-h> - Corrects mistakes <ctrl-c> - Terminates the current command and returns to the
shell <ctrl-d> - End of transmission <ctrl-s> - Temporarily stops output to the screen <ctrl-q> - Resumes output <ctrl-w> - Erase last word <ctrl-u> - Erase the entire line <tab> - Command or filename completion <arrow up> - Previous command <arrow down> - Next command <arrow left> - One character to the left <arrow right> - One character to the right <shift page-up> - Look at the output of previous commands <shift page-down> - Look at the output of later commands;
eventually gets you back to the command prompt <ctrl-r> - Search for a command in the command history
Command History
Command history also can be viewed with history command
$ history 599 clear999 wc .bash_profile1000 wc .bash_profile1001 wc .bash_profile1000 history
Retrieving commands with " ! "
To retrieve commands, use !u
$ wc .bash_profile16 23 238 .bash_profile
Redo previous:
$ !-1 wc .bash_profile 16 23 238 .bash_profile or:
$ !!
Redo command No. 999:
$ !999
Console Mouse Tips
On most distributions, the mouse also works in text mode
Left mouse button o Click: Mark start of selectiono Drag: Mark selection
Middle mouse button o Click: Paste selection
Right mouse button o Click: Mark end of selection
Locking
When temporary leaving a system alone, always lock your terminalOther people might misuse your account
In a text mode terminal, use vlock (lock your terminal) or vlock -a (lock the whole console)
In a graphical mode terminal, use the menu, the "padlock" icon or xlock Most screensavers support automatic locking too
A locked terminal can only be unlocked with the users password
Logging Out
When finished working on a system, always log out Other people might misuse your account
In a text mode terminal, use logout, exit or ctrl-d
In a graphical mode terminal, use appropriate menus
Unit 4 - Working with Files and Directories
A file is: A collection of data A stream of characters or a "byte stream" No structure is imposed on a file by the operating system
File Types
7
Linux Filenames
Should be descriptive of the content Should use only alphanumeric characters UPPERCASE, lowercase,
number, @, _ Should not include embedded blanks Should not contain shell metacharacters: * ? > < / ; & ! [ ] | \ ' " ( ) { } Should not begin with + or - sign Are case sensitive Filenames starting with a . are hidden The maximum number of characters for a filename is 255
Linux Pathnames
Full pathnames: Start from / (the root directory)
Relative pathnames: Start from the present working directory
Examples: working directory is /home/tux1
/home/tux1/doc/mon_report (full)doc/mon_report (relative)../tux3/pgms/suba (relative)./test (a file in the current
dir)~/test (same as above)
Example Directory Structure
Where Am I?
pwd command (print working directory) can be used to find out what your current working directory is:
$ pwd/home/tux1
Change Current Directory
With the cd (change directory) command: $ cd dirname
$ cd doc (relative)$ cd /home/tux1/doc (full)$ cd ~tux1/doc (home)$ cd (Go to your home
directory)$ cd .. (Go one directory up)$ cd - (Go to previous
directory)
Create Directories
With the mkdir (make directory) command: $ mkdir dirname
$ mkdir /home/tux1/doc (full pathname)
$ cd /home/tux1$ mkdir doc (relative pathname)
Removing Directories
With the rmdir (remove directory) command: $ rmdir dirname
$ pwd/home/tux1$ rmdir doc testrmdir: doc: Directory not empty
Note: directory must be empty!
Working with Multiple Directories
Create and remove multiple directories simultaneously with the -p flag
$ mkdir -p dir1/dir2/dir3 or $ mkdir dir1 dir2 dir3
$ rmdir -p dir1/dir2/dir3 or $ rmdir -r dir1 dir2 dir3
List the Contents of Directories
With the ls command: $ ls [dir/file]
$ ls /hometux1 tux2 tux3
Important options:
8
-l long listing (more information)-a lists all files (including hidden)-t lists files sorted by change date-R lists contents recursively
The touch Command
touch command creates an empty file, or updates the modification time of an existing file
$ ls -l-rw-rw-r-- 1 tux1 penguins 512 Feb 24 11:10 docs
$ touch docs$ ls -l-rw-rw-r-- 1 tux1 penguins 512 Mar 5 15:37 docs
$ touch new$ ls -l-rw-rw-r-- 1 tux1 penguins 512 Mar 5 15:37 docs-rw-rw-r-- 1 tux1 penguins 0 Mar 5 15:37 new
Copying Files
cp command copies files: cp [source/s] [target]
Copying one file to another:
$ cp .bashrc bashrc.old
Copying multiple files into a target directory:
$ cp doc/mon_report doc/walrus /tmp
cp can recursively copy directories with the -R flag
$ cp -R /home/tux1/doc /tmp
To prevent cp from overwriting existing files, use:
$ cp -R -i /home/tux1/doc /tmp cp: overwrite `/tmp/doc/walrus´?
Moving and Renaming Files
With the mv command: $ mv [source/s] [target]
To move a file do another directory:
$ mv doc/walrus ../../tmp To rename a file:
$ mv doc documents
Use the -i option to prevent mv from overwriting existing files
Moving and renaming files can be combined by mv:
$ cd$ pwd/home/tux1mv /tmp/walrus ./test/rob
To move a directory:
$ mv ./test /tmp
Note: mv is recursive by default
Listing File Contents
With the cat (concatenate) command: $ cat file1 file2 ...
$ cat walrus"The time has come", the walrus said,"To talk of many things:Of shoes - and ships - and sealing wax -Of cabbage - and kings -And why the sea is boiling hot -And whether pigs have wings."
Displaying Files Page by Page
With the more or less commands: $ [less/more] walrus
"The time has come", the walrus said,"To talk of many things:Of shoes - and ships - and sealing wax -Of cabbage - and kings -And why the sea is boiling hot -And whether pigs have wings."/tmp/test/walrus 1-6/6 (END)
Displaying Binary Files
With the od command:
With the strings command:$ strings /usr/bin/passwd/lib/ld.so.1__gmon_start____deregister_frame_info__register_frame_info...
Removing Files
With the rm command: $ rm test/rob
$ ls test/rob
9
ls: rob: No such file or directory
If unsure, use -i option $ rm -i test/rob rm: remove `test/rob´?
To remove files and directories recursively:
$ rm -ir test/
Splitting Files
You can split a file into smaller files with the split command $ split -b <bytes> file [prefix]
$ ls -l-rw-r--r-- 1 root root 4194304 Feb 21 13:31 large
$ split -b 1024k large large.
$ ls -l-rw-r--r-- 1 root root 4194304 Feb 21 13:31 large-rw-r--r-- 1 root root 1048576 Feb 21 13:33 large.aa-rw-r--r-- 1 root root 1048576 Feb 21 13:33 large.ab-rw-r--r-- 1 root root 1048576 Feb 21 13:33 large.ac-rw-r--r-- 1 root root 1048576 Feb 21 13:33 large.ad
File Managers
Linux also offers different graphical file managers
Nautilus (GNOME) Konqueror (KDE)
Unit 5 - File and Directory Permissions
Permissions
File permissions are assigned to:
owner of a file members of the group the file is assigned to all other users
Permissions can only be changed by the owner and root
Viewing Permissions
To show the permissions of a file, use the ls command with the -l option
Permissions Notation
Required Permissions
Changing Permissions
To change the permission of a file use the chmod command
Syntax: chmod [MODE] [FILE/S]
Mode can be symbolic
$ chmod go-rx /home/tux1$ ls -ld /home/tux1drwx------ 4 tux1 users 512 Jan 5 12:43 /home/tux1
Mode can be octal:
$ chmod 700 /home/tux1$ ls -ld /home/tux1drwx------ 4 tux1 users 512 Jan 5 12:43 /home/tux1
Changing Permissions
10
Calculating numeric (octal) mode:
umask
New files should not be created with 666, to avoid this problem a permission mask exists. Syntax: $ umask 022
Unit 6 - Linux Documentation
The man Command
With the man command you can read the manual page of commands.
Manual pages are stored in /usr/share/man The manual page consists of:
Name - The name of the command and a one-line description Synopsis - The syntax of the command Description - Explanation of how the command works and what it does Files - The files used by the command Bugs - Known bugs and errors See also - Other commands related to this one
Example Manual Pages
The -k option of the man command or the apropos command prints out a description of all entries which match the given keyword
man Sections
Manual pages are divided in 9 sections:
1. User commands2. System calls3. Libc calls4. Devices5. File formats and protocols6. Games7. Conventions, macro packages and so forth8. System administration9. Kernel
Certain subjects appear in multiple sections
To select correct section, add section number: man 1 passwd (about the passwd command) man 5 passwd (about the passwd file)
The info Command
Sometimes a replacement for manual pages Widely used by the GNU project Information for info is stored in /usr/share/info
Some info commands:
space next screen of textdel or bs previous screen of textn next nodep previous nodeq quit info
The --help Option
Another way of getting help about a command Help is built in the command itself (if supported)
11
HOWTO Documents
Documents which describe in detail a certain aspect of configuring or using Linux.
Detailed information about how to perform a given task Install PCMCIA support Kernel compilation Dual boot with other operating systems
HOWTO documents are text files in /usr/share/doc/HOWTONeed to be installed manually
On the Internet: http://www.tldp.org/index.html
Other Documentation
Certain programs also offer other kinds of documentation HTML PostScript Plain Text
Usually stored in /usr/share/doc/<programname>
On the Internet
All Linux documentation is available on the Internet. Google: http://www.google.com/linux Other sites:
http://www.tldp.org http://www.linux.org http://www.redhat.com http://www.suse.com http://www.xfree86.org http://www.kernel.org http://lwn.net and many more
Usenet news: comp.os.linux.* Country-specific groups
Unit 7 - Directory Structure
All Linux directories are contained in one, virtual, "unified file system"
Physical devices are mounted on mount points Floppy disks Hard disk partitions CD-ROM drives
No drive letters like A:, C:, ...
/bin - contains executables for every user
/sbin - contains system administration executables
/lib - contains libraries
Should always be available At system boot In single user mode When booting from rescue disk
/boot - contains kernel image and some other goodies
/dev - Contains special files that represent hardware devices Block special device, for example, a hard disk Character special device, for example, mouse and keyboard
Each device has a major and minor number Identification within the kernel
/etc - contains system-wide configuration files
Some subsystems have multiple files and therefore use a separate directory
/etc/X11 contains X Window System configuration /etc/skel contains default user configuration files /etc/sysconfig contains system configuration
/home - home directories of users
/mnt - mount points for other file systems
Note: SUSE uses /media instead of /mnt for floppy and cdrom mount points
/proc - virtual file system that represents kernel and process information
/root - home directory of the root user
/tmp - temporary storage space for programs, users and usually automatic cleanup mechanism active
/usr (UNIX System Resources)
Contains all programs, libraries and so on which are not essential for system boot and emergency operations
/usr/local intended for programs not in the distribution o locally developedo locally compiled
12
/var
Files of variable sizeo logfileso lockfiles
Directories with variable contento mailo schedulingo printing
Temporary storage space, longer than /tmp
/lost+found
Exists in every file system Place where lost+found files are stored after a crash
recovery by fsck
Other Directories in /
/opt - used for some software from external providers Separate file system advisable
Whatever you create yourself.
Virtual and Unified File System
Linux does not use drive letters (A:, C:, D:) to identify drives/partitions, but creates a virtual, unified file system
Different drivers/partitions are "mounted" on a "mount point"
Typical File System Layout
The mount Command
mount command mounts a file system Makes it part of the unified file system structure
mount [-t type] [-o opts] device mountpnt
# mount /dev/hda5 /usr
The umount Command
umount command unmounts a file system Takes it out of the unified file system structure File system should not be busy
Syntax: umount {device|mountpnt}
# umount /dev/hda5 or # umount /usr
The /etc/fstab File
/etc/fstab lists all known filesystems on the systemSyntax: device mountpoint type options dump fsck
File systems with the noauto option are not mounted automatically but can be used as templates for mount
Note: Some distributions use file system labels instead of device names.
Mounting and Unmounting Removable Media
13
Most distributions configure /etc/fstab so that the console user is allowed to mount removable media (floppy, cd) on a predetermined mountpoint and with predetermined options (for security)
Always unmount media before ejecting
GUI typically offers icons that perform the mount
$ whoamitux1
$ mount /mnt/cdrom$ mount
./dev/cdrom on /mnt/cdrom type iso9660 (ro,nosuid,nodev,user=tux1).
$ ls /mnt/cdrom.$ umount /mnt/cdrom
Unit 8 - Editing Files
Editing Files
Use file command to determine the content of a file
$ file /etc/passwd/etc/passwd: ASCII text
$ file /usr/bin/passwd/usr/bin/passwd: ELF 32-bit LSB executable
To edit text files, use an editor Non-text files can only be changed using the application that created
them, or with a "hex editor" But most configuration files under Linux are text files
The "vi" Text Editor
Default editor in all UNIX operating systems Usually the only editor available in emergencies Relatively hard to learn, but really powerful As a Linux user, you should be able to use vi for basic editing tasks
But it's OK if you prefer another editor for daily work
vi in Linux is usually vim (vi improved): Syntax highlighting Arrow keys, Del, BS work in insert mode Multi level undo Mouse support
vi Modes
vi knows three modes of operation Command mode (for simple, one-letter commands) Edit mode (insert text) ex mode (for complicated commands)
Can easily change between modes
Cursor Movement in Command Mode
Editing Text in Command Mode
x - To delete a single character under cursor x X - To delete a single character left of cursor X r -To replace a single character r u - Undo the last change u . - To repeat last command J - To join two lines together
Switching to Edit Mode
I - To insert text at begin of line i - To insert text before cursor a - To append text after cursor A - To append text at end of line <ESC> - To go back to command mode
Adding Text in Edit Mode
Keystroke "i" switches vi to edit mode. New characters can be inserted at the current position of the cursor
14
Exiting the Edit Mode
Keystroke "ESC" leaves the edit mode.
Searching for Patterns
/pattern - To search for a pattern (in command mode) n - To repeat the previous search
Replacing Patterns
Advanced search and replace can be done in ex mode :1,$s /old/new/g - To replace old with new
Cut, Copy and Paste
dd - To cut a whole line into buffer yy - To copy a whole line into buffer dw - To cut a word from the current cursor position to its end p -To paste contents of buffers here 3dd, 8yy - To cut, copy multiple lines, precede command by
number
Cut and Paste
vi Options
Options entered in ex mode change the behavior of the vi editor:
:set all:set autoindent/noautoindent:set number/nonumber:set list/nolist:set showmode/noshowmode:set tabstop=x:set ignorecase/noignorecase:set wrapmargin=x:set tx/notx:set hlsearch/nohlsearch:syntax on/off
To make these options available to all vi sessions, put it into a .exrc or .vimrc file in your HOME-directory
Exiting vi
ZZ - To save and exit in command mode :w - To save in ex mode :w! - To forcefully save file in ex mode :q - To quit without saving in ex mode :q! - To forcefully exit in ex mode :wq - To save and exit in ex mode (recommended) :x - To save and exit in ex mode, shorter
vi Cheat Sheet
Other Editors
A typical Linux distribution comes with a large number of editors.
15
Examples:
Text mode editors pico (really simple) Original vi emacs (even more powerful and complicated than vi)
Graphical mode editors kedit, kwrite gedit
Hex editors allow you to change non-text files if you know the internal structureKhexedit
Unit 9 - Shell Basics
The Shell
Shell is the user interface to Linux
Shell Features
When the user types a command, various things are done by the shell before the command is actually executed:
Wildcard expansion * ? [ ] Input/Output redirection < > >> 2> Command grouping { com1 ; com2; } Line continuation \ Shell variable expansion $VAR Alias expansion dir -> ls -l Shell scripting #!/bin/bash
For example, the ls *.doc command could be expanded to /bin/ls --color=tty mydoc.doc user.doc before execution (depending on settings and files present)
Metacharacters and Reserved Words
Metacharacters are characters that the shell interprets ashaving a special meaning.
Reserved words are words that the shell interprets as special commands.
Basic Wildcard Expansion
When the shell encounters a word which contains a wildcard, it tries to expand this to all matching filenames in the given directory
Advanced Wildcard Expansion
wildcards [, ], - and ! match inclusive lists:
File Descriptors
Every program has a number of file descriptors associated with it Three descriptors are assigned by the shell when the program starts
(STDIN, STDOUT and STDERR) Other descriptors are assigned by the program when it opens files
Input Redirection
16
Default Standard Input: $ cat
AmsterdamAmsterdamUtrechtUtrecht<ctrl-d>
STDIN redirected from file:
$ cat < citiesAmsterdamUtrecht$
Output Redirection
Default Standard Output: /dev/tty
$ lsfile1 file2 file3
Redirect output to a file:
$ ls > ls.out
Redirect and append output to a file:
$ ls >> ls.out
Create a file with redirection:
$ cat > new_fileSave this line<Ctrl-D>
Error Redirection
Default Standard Error: /dev/tty
$ cat fileacat: filea: No such file or directory
Redirect error output to a file:
$ cat filea 2> error.file$ cat error.filecat: filea: No such file or directory
Redirect and append errors to a file:
$ cat filea 2>> error.file
Discard error output:
$ cat filea 2> /dev/null
Combined Redirection
Pipes
A sequence of two or more commands separated by a vertical bar (|) is called a pipe or pipeline
$ ls -l | wc -l
The standard output of command1 becomes the standard input of command2
Filters
Filter is a command that reads from standard in, transforms the input in some way and writes to standard out.
They can, therefore, be used at intermediate points in a pipeline.
$ ls | grep .doc | wc -l4
Common Filters
expand, unexpand - Change tabs to spaces and vice versa
sed - Allows string substitutions awk - Pattern scanning and processing fmt - Insert line wraps so text looks pretty tac - Display lines in reverse order tr - Substitute characters grep - Only displays lines that match a pattern nl - Number lines pr - Format for printer sort - Sort the lines in the file
Split Output
tee command reads standard input and sends the data to both standard out and a file.
17
$ ls | wc -l3
$ ls | tee ls.save | wc -l3
$ cat ls.savefile1file2file3
Command Substitution
Command Substitution allows you to use the output of a command as arguments for another command.
Use backticks (`) or $() notation:
$ rm -i `ls *.doc | grep tmp`$ echo There are $(ps ax | wc -l) processes running.
Command Grouping
Multiple commands can be entered on the same line, separated by a semicolon (;)
Commands can be grouped into one input/output stream by putting curly braces around them:
Commands can be executed in a sub shell by putting round braces around them:
$ date ; pwd$ ( echo Print date: ; date ; cat cities ) | lpr$ { echo Print date: ; date ; cat cities; } | lpr
Shell Variables
Variables are part of the environment of a process A variable has a unique name The first character must not be a digit. To assign a value to a variable use: variable=value
$ VAR1="Hello class"$ VAR2=2
Referencing Shell Variables
To reference the value of a variable, use:
$variable$ echo $VAR1Hello class$ echo $VAR22
Exporting Shell Variables
The export command is used to pass variables from a parent to a child process.
Changes made to variables in a child process do not affect the variables in its parent.
$ export x=4$ bash$ echo $x4
$ x=100$ echo $x100
$ exit$ echo $x4
Standard Shell Variables
The shell uses several shell variables internally These variables are always written in uppercase
Example:
$ - PID of current shell PATH - Path which is searched for executables PS1 - Primary shell prompt PS2 - Secondary shell prompt PWD - Current working directory HOME - Home directory of user LANG - Language of user
Overwriting these variables by accident can cause unexpected results
Always use lowercase variables in your own shell scripts to avoid conflicts
Return Codes from Commands
A command returns a value to the parent process. By convention, zero means success and a non-zero value means an error occurred.
A pipeline returns a single value to its parent The environment variable ? contains the return code of
the previous command.
$ whoamitux1
$ echo $?0
$ cat fileacat: filea: No such file or directory$ echo $?1
Quoting Metacharacters
When you want a metacharacter NOT to be interpreted by the shell, you need to quote it
Quoting a single character is done with the backslash (\)
18
Quoting a string is done with single (') or double (") quotes
Double quotes allow interpretation of $, `(backtick) and \
$ echo The amount is US\$ 5The amount is US$ 5$ amount=5
$ echo 'The amount is $amount'The amount is $amount
$ echo "The amount is $amount"The amount is 5
Quoting Non-Metacharacters
The backslash can also be used to give a special meaning to a non-metacharacter (typically used in regular expressions)
\n = newline\t = tab\b = bell
A backslash followed directly by Enter is used for line continuation
The continued line is identified with the $PS2 prompt (default: >)
$ cat/home/john/mydir/mysudir/data/information/letter\> /pictures/logo.jpg
Aliases
The alias command allows you to set up aliases for often-used commands
Examples:
$ alias ll='ls -l'$ alias rm='rm -i'
To show all currently defined aliases:$ alias
To delete an alias:
$ unalias ll$ llbash: ll: command not found
Unit 10 - Working with Processes
What is a Process?
A program is an executable file A process is a program which is being executed Each process has its own environment:
To see the PID of your current shell process type:
$ echo $$
Starting and Stopping a Process
All processes are started by other processes Parent/Child relationship
$ ls –l
A process can be terminated because of two reasons: The process terminates itself when done The process is terminated by a signal from another
process
Login Process Environment
Parents and Children
$ echo $$561
$ bash$ echo $$675
$ dateThu Mar 25 22:28:21 CET 1999$ <ctrl-d>
$ echo $$561
19
Monitoring Processes
The ps command displays process status information
ps supports a large number of options - you typically use ps aux:
a - all processes attached to a terminal x - all other processes u - provides more columns
options are typed without a leading "-" !
Viewing Process Hierarchy
pstree shows process hierarchy
Controlling Processes
Processes can be controlled in two ways:
From the shell that started it, using its job number From anywhere else on the system, using its PID
Actions that can be performed on a running process: Terminate Kill Stop/Continue
These actions are performed by sending signals
Starting Processes
Foreground processes are invoked by simply typing a command at the command line.
$ find / -name README
Background processes are invoked by putting an "&" at the end of the command line
$ find / -name README &
Job Control in the Bash Shell
<ctrl-z> - suspends foreground task jobs - lists background or suspended jobs fg - resume suspended task in the foreground bg - resume suspended task in the background
Specify a job number for bg, fg and kill using %job
Kill Signals
Several signals can be sent to a process
Using keyboard interrupts (if foreground process) Using the kill command
Synopsis: kill -signal PID
Using the killall command to kill all named appsSynopsis: killall -signal application
Most important signals:
20
Running Long Processes
The nohup command will stop a process from being killed if you log off the system before it completes, by intercepting and ignoring the SIGHUP and SIGQUIT (hangup and quit) signals
$ nohup find / -name README &nohup: appending output to `nohup.out´$ logout
Managing Process Priorities
Processes are scheduled according to priority
The nice Command
The nice command is used to start a process with a user defined priority$ nice [-n <value>] <original command>
The renice Command
The renice command is used to change the priority of a currently running process
$ renice <new_priority> <PID>
Integrated Process Management
Various integrated tools exist for process management top, gpm, kpm
Availability depends on distribution
Daemons
The word "Daemon" refers to a never-ending process, usually a system process that controls a system resource such as the printer queue or performs a network service
Unit 11 - Linux Utilities
The find Command
Search one or more directory structures for files that meet certain specified criteria
21
Display the names of matching files or execute commands against those files
Syntax: $ find path expression
Sample Directory Structure
Using find
Generally, you want to search a directory structure for files with certain names and list the names found.
$ cd /home/joe$ find . -name phone./shape/phone./phone
On many other UNIX systems, with find you have to tell it specifically to print the names using -print
$ find . -name phone -print./shape/phone./phone
Executing Commands with find
The -exec option executes a command on each of the file names found.
$ find . -name 'b*' -exec ls -i {} \;187787 ./color/blue187788 ./color/brown187792 ./shape/box202083 ./size big132754 ./blues
" { } " is a placeholder for each filename. The backslash escapes the following semicolon.
Interactive Command Execution
The -ok option also causes command execution but on an interactive basis:
$ find . -name b\* -ok rm {} \;< rm ... ./color/blue > ? y< rm ... ./color/brown > ? y< rm ... ./shape/box > ? y< rm ... ./size/big > ? y< rm ... ./blues > ? y
Additional find Options
find Examples
locate Command
locate allows you to quickly find a file on the system, based on simple criteria
$ locate passwd/usr/share/man/man1/passwd.1.gz/usr/share/man/man5/passwd.5.gz/etc/passwd/usr/bin/passwd
Requires that the superuser runs updatedb regularly Most distributions run updatedb automatically SuSE does not install locate/updatedb by default
The cut Command
Pull selected columns or fields from one or more files.
22
Syntax: cut -f(ields) -d(elimiter) file(s)cut -c(haracters) file(s)
The grep Command
Searches one or more files or standard input for lines matching pattern
Simple match or Regular Expression
Syntax: grep [options] pattern [file1 ...]
grep Sample Data Files
Basic grep
grep with Regular Expressions
Patterns with metacharacters should be in single quotes (' ') so that the shell will leave it alone
Valid metacharacters with grep: $ . * ^ [ - ] . - Any single character * - Zero or more occurrences of the preceding
character [a-f] - Any ONE of the characters in the range a
through f ^a - Any line that starts with a z$ - Any line that ends with z
grep Options
-v - Print lines that do not match-c - Print only a count of matching lines-l - Print only the names of the files with matching lines-n - Number the matching lines-i - Ignore the case of letters when making comparisons-w - Do a whole word search-f <file> - Read expressions from file instead of command line
Other greps
fgrep allows only fixed strings (no regular expressions) egrep allows for multiple (alternate) patterns
$ egrep '20500|40599|50599' phone1Judith 20500 internLeo 40599 externNannie 50599 extern
The sort Command
The sort command sorts the lines in the file specified and writes the result to standard output
Syntax: sort -t(delimiter) +field -options file
23
$ cat animalsdog.2cat.4penguin.10
$ sort animalscat.4dog.2penguin.10
$ sort +0.1 animalscat.4penguin.10dog.2
$ sort -t. +1 animalspenguin.10dog.2cat.4
$ sort -t. -n +1 animalsdog.2cat.4penguin.10
Options:
-d - sorts in dictionary order. Only letters, digits and spaces are considered in comparisons-r - reverses the order of the specified sort-n - sorts numeric fields in arithmetic value
The head and tail Commands
The head command can be used to view the first few lines of a file or files. The command syntax is:
Syntax: $ head [-lines] file(s)
The tail command displays the last few lines of a file or files.
The command syntax is: $ tail [{-lines|+lines|-f}] file(s)
$ head -5 myfile$ ls -l | head -12$ tail -20 file$ tail +20 file$ tail -f file
The type, which and whereis Commands
To find out what the path to a command is, use type
$ type find echofind is /usr/bin/findecho is a shell builtin
To find out where the binary is located, use which
$ whereis find echofind: /usr/bin/find /usr/man/man1/find.1echo: /bin/echo /usr/man/man1/echo.1
To locate the binary, source and manual page files of a command, use whereis
$ which find echo/usr/bin/find/bin/echo
The file Command
With the file command, you can find out what the type of data in the file is.
$ file /etc/passwd /bin/ls /home/peter /tmp/fake.jpg/etc/passwd: ASCII text/bin/ls: ELF 32-bit LSB executable, Intel 80386,version 1, dynamically linked, stripped/home/peter: directory/tmp/fake.jpg: PDF document, version 1.3
The gzip, gunzip and zcat Commands
To compress or uncompress files use gzip, gunzip or zcat
The join and paste Commands
join and paste combine files
The Linux Graphical User Interface
The "X Window System" is the GUI of Linux Developed at MIT in 1984 Current standards body: X Consortium
24
Shortname: X
X uses client-server model with network connections Highly flexible Easy exchange of components Supports networked applications and sessions,
independent of the OS
X Components
X Server
Controls keyboard, mouse and one or more screens Controls resolution, refresh rate and color depth Allows simultaneous access by several clients Performs basic graphic operations Forwards keyboard and mouse events to the correct
clients
X Client
Is for instance an application Receives keyboard and mouse inputs from server Sends output to be displayed to server
Window Manager
Is a special X Client Performs "windows dressing" on other clients Allows other client windows to be moved, iconified
and so forth
X Servers in Linux
Most distributions use XFree86 (www.xfree86.org) as their X Server
Open Source Supports most video adapters
Other X Servers for Linux are available as well
Metro-X (http://www.metrolink.com) Xi Graphics (http://www.xig.com)
XFree86 Configuration
XFree86 needs to be configured for your hardware
Keyboard Mouse Graphical adapter Monitor
Things to configure: refresh rate, resolution, color depth Config file: /etc/X11/XF86Config Manual configuration possible, but hard
See XFree86-HOWTO for details
Automated configuration tools available:
During installation of distribution XFree86 tools: xf86config, X -configure Distribution tools: redhat-config-xfree86 (Red Hat and Fedora), sax2/yast2 (SuSE)
Desktop Environments
Desktop Environment is: A set of tools, libraries and standards that allows
rapid development of X clients A set of X clients (including one or more window
managers) that are developed with these tools, libraries and standards
Examples:
GNOME (GNU Network Object Model Environment)KDE (K Desktop Environment)
Advantages of Desktop Environments
Integration (cut & paste via clipboard, drag & drop) Common look (themes)
Starting X
If logged in on a text terminal, run startx
Only starts a single session When session ends, you are back in your text
terminal
If you want to enable the graphical login screen, bring the system into runlevel 5
25
To switch manually use init 5 command To make change permanent, edit
/etc/inittab: id:5:initdefault:
Choosing your Desktop Environment
Most distributions provide multiple desktop environments To choose between them, select from the Login prompt Every user can have his/her own preference
Unit 14 - Customizing the User Environment
Bash Initialization (Login Shell)
/etc/profile$HOME/.bash_profile-or- $HOME/.bash_login-or- $HOME/.profile$ Bourne Again Shell$HOME/.bash_logout
Bash Initialization (non-Login Shell)
Bash Initialization with Redhat Extensions
Bash Initialization with SuSE Extensions
Unit 15 - Basic System Configuration
Why System Configuration
Most system configuration is done during installation Might need to change system configuration afterwards:
Things not configured during installation Configuration failed during installation Environment changed after installation
Three ways to change system configuration
Temporary - until next system reboot Manually - changing config files by hand Automated - using system administration tools
Typical items to be configured on a workstation:
Add/remove software Printers Sound Cards Network
26
System Configuration Tools
Various tools have been developed to ease system administration
Application specific (Samba SWAT, ...) Distribution specific (redhat-config-*, SuSE yast, ...) Desktop Environment specific (gmenu, kcontrol, ...) Generic Linux/UNIX (webmin, ...)
Adding/Removing Software using RPM
Use rpm to install or upgrade software packages Common options:
-i - installing new packages -U - upgrading existing packages -e - removing packages
$ rpm -ihv myprog-1.2-34.i386.rpmmyprog ###############....
$ rpm -Uhv myprog-1.2-78.i386.rpmmyprog ###############.....
$ rpm -e myprog
The -h options shows a progress bar
Querying the RPM Database
Options:
-i - list information -l - list all files -p - queries new packages before installing
Adding/Removing Software from a .tar.gz File
.tar.gz (.tgz) - default distribution format for source code
tar = "tape archiver": stores a directory tree in a single file
gz = "GNU Zip" - compression program
To unpack a .tar.gz or .tgz archive:
cd /usr/srctar -zxvf archive-version.tar.gzcd <archivename>
Read INSTALL or README file for installation instructions
Should be installed under /usr/local
Printer Configuration
On Red Hat, Fedora and SuSE, the printer subsystem is CUPS (Common UNIX Printing System)
Configuration done through lpadmin or with a browser (http://hostname:631/) (recommended!)
Sound Card Configuration
Configuration usually done with dedicated tool Red Hat, Fedora: redhat-config-soundcard SuSE: yast2 or alsaconf
Sound Card support requires correct loading of kernel modules!
Network Configuration
Need correct network module to be loaded into kernel
/etc/modules.conf
Need to set correct IP addresses etc.
Generally done with ifconfig command For DHCP, use dhcpcd, pump or dhclient
Configuration done through scripts which are different in each distribution
27
Red Hat, Fedora: /etc/sysconfig/network-scripts/ifcfg-eth0
SuSE: /etc/sysconfig/network/ifcfg-eth0
Use distribution specific tool to configure
Red Hat, Fedora: redhat-config-network SuSE: yast
Unit 16 - Connecting to the Internet
Connecting to the Internet
Connecting to the Internet = Establishing a channel which allows you to send IP packets to your ISP and vice versa
Four most common connection types:
Regular modem connection ISDN connection Cable modem connection xDSL connection
Connection types differ in:
Cost (one-time, fixed and variable) Bandwidth, Latency Availability Additional features such as fixed IP addresses
Modem Connections
Use an analog telephone line to establish a digital data connection (MOdulation/DEModulation)
PPP is used for IP packet encapsulation between your PC and the ISPs router
Modem Connections in Linux
External modems have device names /dev/ttySn
COM1 = ttyS0, COM2 = ttyS1
Internal modems usually emulate a serial port – nothing special
Winmodems require a software driver which is usually only available under Windows (with a few exceptions)
To setup connection, need to invoke pppd Best done using a graphical front end such as kppp
ISDN Principles
ISDN (Integrated Services Digital Network)
Provides a 100% digital network Popular in Europe
Most popular variant for home use is ISDN-2 2 channels, 64 Kbps each
One ISDN-2 connection can have up to eight Multiple Subscriber Numbers (MSN)
ISDN in Linux
Linux implements pseudo-tty's which accept regular modem commands to set up ISDN connections
/dev/ttyI0 through /dev/ttyI63 Can be used just like a modem in your Internet dialer Need a special AT command to configure MSN:
AT&E0123456789
Applications can also access the ISDN adapter directly
Requires an ISDN-capable dialer such as isdn-config Supports channel bundling Automatically configures MSN
28
More documentation: /usr/src/linux/Documentation
Cable Modems Principles
Cable modems use available, but unused frequency ranges in the cable TV network
Typical bandwidth: 30 Mbps shared Connecting requires a "cable modem"
xDSL Principles
Generic name for utilizing additional bandwidth in "local loop" of telephone network
Various implementations: ADSL, HDSL, SDSL, ... Bandwidth is dependent on implementation, phone line
quality and distance Connecting requires a splitter or filters, and an xDSL
modem
Cable and xDSL in Linux
Most cable and xDSL modems connect to your Linux PC via a small Ethernet network, and bridge/route traffic into the ISPs network
Other connection types are possible too, but less common: USB, serial, wireless (not covered here)
Configure your Ethernet adapter as directed by the ISP
Static IP address DHCP
Internet Security
Being connected to the Internet is a security risk Especially with an "always on" connection (cable,
xDSL...)
Every workstation needs basic security measures Good passwords No unneeded services running Latest versions of all services that are running
To determine network services that are running: To disable unneeded services:
# chkconfig <SERVICE> off
Never start your browser as root! Never log in to your system as root (unless needed)!
# netstat –anutp
Unit 17 - Integrating Linux in a Windows Environment
Linux: Unified File System
Virtual directory tree All physical file systems are "mounted"
Windows: Drive Letters for each separate File system
29
Mounting Windows File Systems
To mount the first primary partition on your first IDE hard disk on the mount point /mnt/win95:
# mount /dev/hda1 /mnt/win95...or# mount -t vfat /dev/hda1 /mnt/win95
All files on your C:- disk are now accessible in /mnt/win95
Make permanent by adding this to /etc/fstab:
Accessing Windows File Systems Directly
mtools is a collection of tools that can read/writeWindows file systems directly, using drive letters.
# mcopy c:autoexec.bat /root/autoexec.bat# mformat a:# mdir a:
Devices must not be mounted! Drive letters are mapped to physical devices in
/etc/mtools.conf:
drive a: file="/dev/fd0" exclusive 1.44m mformat_only
drive c: file="/dev/hda1"
Running Windows Programs
To run a Windows program, the underlying Windows OS needs to be emulated
Can be done at two levels: Emulate a PC and install Windows on it Emulate Windows itself
Note that you need a license for Windows if you use anyWindows software (including single DLLs)
PC Emulators
Emulate a PC on which you install Windows Do need a Windows license
Bochs (http://bochs.soundforge.net) Emulates a complete PC in software Can run under any POSIX compatible OS Can run on any architecture Open Source
Big performance loss
VMWare (http://www.vmware.com) Emulates a complete PC in software Only runs on Linux/Intel or Windows NT/Intel Commercial Product About 30% performance loss
Windows Emulators
win4lin (http://www.netraverse.com) Commercial product Emulates Windows kernel Needs Windows DLLs Needs Windows license
WINE - WINdows Emulator (http://www.winehq.com) Open Source product Does not need a Windows license if only WINE or
third party DLLs are used Can use Windows DLLs (beware of license!) To see if your application is supported, go to Web site
CrossOver Office (http://www.codeweavers.com) commercial extension to WINE
Accessing Windows Servers
Samba (http://www.samba.org) Open Source product Runs on any UNIX Used to replace a Windows server (not covered here) Also includes a number of client tools: smbclient, smbmount, smbprint
smbclient allows you to retrieve information about a Windows server, and to access files "ftp-style"
smbmount allows you to mount Windows shares over the network
smbprint allows you to print documents to a Windows-attached printer
smbclient Examples
# smbclient -L winserver -N# smbclient -L winserver -U user# smbclient -L winserver -U user%password# smbclient //winserver/share -U user%pwsmb> get file1smb> put file2smb> quit
Options:
-L - lists the shares on the server
30
-N - guest access -U - qualified access
smbmount Examples
To mount a share as an file system:
Make permanent by adding this to /etc/fstab:
smbprint
smbprint is usually not called directly but integrated into printer spool mechanism
Configure using the regular printer configuration tools Select "SMB Printer" Configure servername, printer name, printer type,
username and password
After configuration the new printer can be used as a normal printer
Reading Windows Document Formats
Most native office programs for Linux read and save Windows document formats
StarOffice/OpenOffice koffice AbiWord
$ file mytext.docmytext.doc: Microsoft Office Document$ swriter mytext.doc
Note that not all document features may be supported
Other Useful Programs
rdesktop - Connect to a Windows Terminal Server
vnc - Allows you to "take over" a Windows systems screen remotely
dos2unix and unix2dos - Convert Windows text files (CR/LF) to UNIX text files (LF)
cygwin (http://www.cygwin.com) - Series of Linux tools running under Windows
31