rh033

264
 1 Redhat Enterprise Linux Essentials

Upload: himanshu-saxena

Post on 04-Nov-2015

4 views

Category:

Documents


0 download

DESCRIPTION

BOOK

TRANSCRIPT

  • *Redhat Enterprise Linux Essentials

    (C) Mustafa Golam, 2007

  • Redhat Linux EssentialsOverview*

    (C) Mustafa Golam, 2007

  • Certified with Leading OEM and ISV ProductsISV Independent Software VendorOEM Original Equipment ManufacturerABI/API Compatibility Application Binary InterfaceApplication Programming Interface ELF Executable and Linking FormatLSB Linux Standards BaseBEA BEA System Inc, San Jose, California. Think LiquidHPC High Performance Computing*

    (C) Mustafa Golam, 2007

  • UNIX from AT&T, at Bell Labs, in 1969.AIX from IBMHP/UX from Hewlett-PackardSunOS (Later Solaris) from SunIRIX from SGI (Silicon Graphics)

    *

    (C) Mustafa Golam, 2007

  • Everything is a file.Including hardwareConfiguration data stored in textSmall, single-purpose programsAvoid Captive User InterfacesAbility to chain programs together to perform complex tasks.*

    (C) Mustafa Golam, 2007

  • GNU Project started in 1984Goal : Create Free UNIX cloneBy, 1990, Nearly all required userspace application created.gcc, emacs etc.Free Software FoundationNon-profit Organization that manages the GNU ProjectFour Freedomshttp://www.gnu.org/philosophy/free-sw.html

    *

    (C) Mustafa Golam, 2007

  • Primary license for Open Source SoftwareEncourages free softwareAll enhancements and changes to GPL-software must also be GPLOften called CopyLeftAll rights Reversedhttp://www.gnu.org/copyleft/gpl.htmlX Window System, has its own T&C.BSD code need to be abide the terms of Berkeley Software Distribution. Visit http://www.bsd.com

    *

    (C) Mustafa Golam, 2007

  • Linux TorvaldsFinish College Student in 1991Created Linux KernelWhen Linux Kernel Combined with GNUApplications, complete free UNIX-like OS possible.*

    (C) Mustafa Golam, 2007

  • Fresh Implementation of UNIX APIs.Open Source Development model.Supports wide variety of hardware.Supports many networking protocols and configurations.Fully supported.Linux is a UNIX-like OS.Multi-user and Multi-tasking.Wide hardware support. Checklist.Fully Supported.*

    (C) Mustafa Golam, 2007

  • A distribution of LinuxCustom version of a recent Linux Kernel.Utilities and applications.Installation and configuration softwareSupport available.RHEL includes installation and configuration software, a patched and rigorously tested recent version of the Linux Kernel, and thousands of utilities and applications.gdm is the default display manager for RHEL.*

    (C) Mustafa Golam, 2007

  • Pentium Pro or better with 256 MB RAMOr64-bit Intel/AMD with 512 MB RAM2-6 GB Disk SpaceBootable CDOther processor architectures supportedItanium 2, IBM Power, IBM Mainframe.*

    (C) Mustafa Golam, 2007

  • Virtual Consoles are available through CTRL ALT F[1-6]If X is running, it is available as CTRL ALT F7The virtual consoles enable a user to have multiple logins even when not using an X Window system.You can scroll at the virtual consoles by using SHIFT-PAGEUP and SHIFT-PAGEDOWN. The scroll buffer is stored in video memory, so if you are running a graphical program such as X, the scroll buffer is lost.*

    (C) Mustafa Golam, 2007

  • The goal of X.Org include a faster and more open development model than Xfree86, support for a wide variety of video cards and input devices and the development of a highly modular and flexible graphical framework for Unix and Linux. http://xorg.freedesktop.org Orhttp://www.x.org/wikiX Client activity that spawns an X server event informing the web browser to send an HTTP request to the links target ( or anchor). You do not really see the X server, but X clients.X provides the data I/O infrastructure for X clients, like a human nervous system, it sends messages when touched by client activity.An X Client running on one system can display on any X server running on any operating system, if sufficient access is granted.For each managed display, this socket is /tmp/.X11-unix/X# where # is 0 to the greatest number of permitted connections.*

    (C) Mustafa Golam, 2007

  • Collections of applications that provide a graphical working environment with a consistent look and feel.GNOME (GNU Network Object Model Environment) The default desktop environment.KDE ( K before L) Environment based on the Qt toolkit.*

    (C) Mustafa Golam, 2007

  • Nothing needed if system boots to a graphical login. Just authenticate.If system boots to a virtual console login, Xorg must be started manually.Run startx to manually start Xorg.Changing Password.At least 6 but no more that 255 characters.Other criteria depends on particular OS.*

    (C) Mustafa Golam, 2007

  • Running Commands and Getting Help*

    (C) Mustafa Golam, 2007

  • --helpwhatis -- with makewhatis maninfo/usr/share/doc/html/en/Software source codeDocumentations*

    (C) Mustafa Golam, 2007

  • Commands have the following syntax:Command [ options] [arguments]Each item is separated by a space.Options modify the commands behaviorWord options usually preceded by --Single-letter options usually preceded by -Can be passed as -a b c or -abcArguments are filenames or other date needed by the commands.

    *

    (C) Mustafa Golam, 2007

  • Anything in straight braces ([]) is optional.Anything followed by represents an arbitrary-length list of that thing.If you see multiple options separated by pipes (|), it means you can use any one of them.Text in straight brackets() represents variable date. So means insert the filename you wish to use here. Sometimes, such variables are simply written in all CAPS.*

    (C) Mustafa Golam, 2007

  • The collection of all man pages on a system is called the Linux Manual. The Linux is divided into sections, each of which covers a particular topic, and every man page is associated with exactly one of these sections.The sections are:Manual Sections.1 User Commands 2 System Calls3 Library Calls4 Special Files5File Formats6Games7Miscellaneous 8Administrative Commandsman and man k commands

    *

    (C) Mustafa Golam, 2007

  • info pages are structured like a website.Each page is divided into nodes.Links to nodes are preceded by *.info []If you run info with no arguments you will be presented with a list links to the top nodes of every available info page.*

    (C) Mustafa Golam, 2007

  • While viewing an info pageNavigate with arrows, pgUp, pgDownTab Move to next linkEnter Follow link the cursor is onn/p/uView next/previous/up-one nodes[]Search for text (default: last search)qQuit Viewing pageIf you prefer the navigation keys used by man, such as using /, n and N to search, you can start info with the vi-keys arguments.

    *

    (C) Mustafa Golam, 2007

  • /usr/share/dochttp://www.redhat.com/docs*

    (C) Mustafa Golam, 2007

  • man f foo is the same as whatis foo.If your system has just been installed, neither man f nor whatis will work until an administrator runs makewhatis.ls lh *

    (C) Mustafa Golam, 2007

  • Browsing the File system*

    (C) Mustafa Golam, 2007

  • Files and directories are organized into a single-rooted inverted tree structure.Filesystem begins at the root directory, represented by a lone / (Forward slash) character.Names are case-sensitive.Paths are delimited by /.A users path is a list of directories that are searched for commands typed at the command line.*

    (C) Mustafa Golam, 2007

  • The essential binaries necessary to boot and maintain the system reside in /bin for regular binaries and /sbin for system binaries.Non-essential binaries, such as graphical environments, web browsers, office tools and so forth, are installed in /usr/bin and /usr/sbin.On a newly installed system, there will also be /usr/local/bin and /usr/local/sbin directories, but they will be empty.CD-ROM is mounted under /media/cdrom folder.Filesystems that are on non-removable media but are not part of the RHEL, hierarchy are usually mounted under /mnt. Visit http://www.pathname.com/fhs*

    (C) Mustafa Golam, 2007

  • /etc -System Configuration Files/tmp-Temporary files/boot-Kernel and boot loader/var and /svr-Server data/proc and /sys-system InformationThe lib directories /lib, /usr/lib, /usr/local/lib*

    (C) Mustafa Golam, 2007

  • Once a day the system automatically deletes any files over seven days old in /tmp and its subdirectories.The /var directory contains regularly-changing system files such as logs, print spools and email spools.In the future, server data may be moved to the /srv directory so that /var only contains logs, spools and so forth.Each shell and system process has a current working directory (cwd).*

    (C) Mustafa Golam, 2007

  • Names may be up to 255 characters.All characters are valid, except the /.It may be unwise to use certain specialcharacters in file or directory names.Some characters should be protected with quotes when referencing them.Names are case sensitive.Example: MAIL, Mail, mail and mAiL Again, possible but may not be wise.To access a file with name contains special characters, enclose the filename in quotes.*

    (C) Mustafa Golam, 2007

  • Absolute pathnames begin with a slash (/)Complete road map to file location.Can be used anytime you wish to specify a file name.To change to your previous working directory$ cd A dash (-) represents your previous working directory. Its a handy shortcut to use to switch back and forth between two directories.*

    (C) Mustafa Golam, 2007

  • cp copy files and directoriesUsage:cp [options] file destinationMore than one file may be copied at a time if the destination is a directory.cp [options] file1 file2 destIf final argument is an existing directory, a copy of the source files are placed in that directory with the same name as the source. Otherwise, the destination is interpreted as a file name, and a copy of the source file is created with that.*

    (C) Mustafa Golam, 2007

  • When copying a single file to a destination, cp first checks to see if a directory exists with the destination name. If it does, a copy of the source file is placed there with its original name.If not, the destination is assumed to be a new file name, and a copy of the source file is made with the destination name.*

    (C) Mustafa Golam, 2007

  • mv move and/or rename files and directories. Usage:mv [options] file destinationMore than one file may be moved at a time if the destination is a directory.mv [options] file1 file2 destIf the destination directory does not exit, the slash will cause the command to fail with an error message.If the destination directory does not exist (but the destination pathname is valid), the source directory will be moved to the destination directory with the new name.*

    (C) Mustafa Golam, 2007

  • rm remove filesUsage:rm [options] filenames-i interactive-r recursive-f forcetouch create empty files or update file timestampsThe r option tells rm to remove files recursively and thus it will delete directories and their contents.There is no way to undo the effects of rm, except to restore from a backup.rmdir will only remove empty directories. To remove a directory and its contents, use rm r.*

    (C) Mustafa Golam, 2007

  • Gnome graphical Filesystem browserCan run in Spatial or Browser modeAccessed via Desktop iconsHome:Your home directoryComputer:Root Filesystem, network resourcesand removable media.File Browser option on Application menu.Typing CTRL-SHIFT-w closes all parent windows.Spatial or Browser Mode can be edited.

    *

    (C) Mustafa Golam, 2007

  • Drag and DropLeft-button: Move on same filesystem, copy on different system.Ctrl-Left-button : Always CopyCtrl-Left-button: Ask whether to copy, move or create symbolic link (alias)Context MenuRight-click or rename, cut, copy or paste.

    *

    (C) Mustafa Golam, 2007

  • Files can contain many types of data.Check file type with file before opening to determine appropriate command or application to use.Syntaxfile [options] filename(s)file prints its best guess of the type of data contained in a file whose name is given as an argument. It bases its guess on a comparison of the contents of the file and the patterns and offsets in its reference file, /usr/share/magic.*

    (C) Mustafa Golam, 2007

  • Syntax:cat [options] [files..]Contents of the files are displayed sequentially with no break.Files display concatenated.-A Show all characters, including control characters and non-printing characters.-s Squeeze multiple adjacent blank lines into a single blank line.-bNumber each (non-blank) line of output.*

    (C) Mustafa Golam, 2007

  • Syntax:less [options] [filename]Scroll with arrows/pgUp/pgDownUseful commands while viewing:/text --search for textn--next matchv -- open file in text editor.less is the pager used by man

    *

    (C) Mustafa Golam, 2007

  • Less navigation commands:move ahead one full screenmove ahead one linemove ahead (down) half a screengmove to the top of the file./textsearch forward for textnrepeat last searchqquitbmove back one full screenkmove back one linemove back (up) half a screenGmove to the bottom of the file?textsearch backward for textNrepeat last search, but in opposite direction.vopen file in a text editor (vi by default)*

    (C) Mustafa Golam, 2007

  • -cClear before displaying. Screen is redrawn instead of scrolled between screens.-rDisplay raw control characters. (May cause display problems)-s squeeze multiple blank lines into a single blank line-eExit the second time it reaches the end of the line.-mVerbose prompt, like more (by default it uses a colon).*

    (C) Mustafa Golam, 2007

  • The bash Shell*

    (C) Mustafa Golam, 2007

  • Bourne Again ShellSuccessor to sh, the original Unix shellDeveloped for the GNU ProjectThe de factor standard Linux ShellBackward-compatible with Bourne shell (sh)- the original (Standard) UNIX shell*

    (C) Mustafa Golam, 2007

  • Bourne Again Shell (bash)Implements many of the best features from earlier shells: sh, csh, ksh , tcshCommand line completionCommand line editingCommand line historySophisticated prompt control*

    (C) Mustafa Golam, 2007

  • Globbing is wildcard expansion:* - matches zero or more characters? matches any single character[a-z] matches a range of characters[^a-z] matches all except the range.The use of wildcards, or metacharacters, allows one pattern to expand to multiple filenames by a process called globbing. RHEL uses UTF-8 encoding of characters, which means that each capital letter comes directly after the corresponding lower-case letter.Use echo ?o* to find the effect of wild characters. *

    (C) Mustafa Golam, 2007

  • The TAB Keyhistory!! to repeat last command!c to repeat last command that started with c!n to repeat a command by its number in history output!?abc to repeat last command that contains (as opposed to started with) abc!-n to repeat a command entered n commands back.User ^old^new to repeat the last command with old changed to new. Tilde(~)May refer to your home directory ( ~/.bash_profile)May refer to another users home directory. (~gmustafa/.bashrc)*

    (C) Mustafa Golam, 2007

  • Parameter/Variable: ($)Substitute the value of a variable in a command line.$ cd $HOME/public/htmlTo see a list of variables and their values, run the set command. Curly braces: { }A string is created for every pattern inside the braces regardless if any file exists.$ rm hello.{c,o}Curly braces are useful for generating patterned strings.*

    (C) Mustafa Golam, 2007

  • Command Output or $ ()Substitute output from a command in a command line.$ echo Hostname: `hostname`$ echo Hostname: $(hostname)Arithmetic - $[]Substitute result of arithmetic expression in a command line.$echo Area : $[$X * $Y]$echo Area : `expr $X\*$Y`

    *

    (C) Mustafa Golam, 2007

  • Backslash (\) is the escape character and makes the next character literal.$echo Your Cost :\$5.00Used as last character on line to Continue command on next line$find / -name foo*$find / -name foo\**

    (C) Mustafa Golam, 2007

  • Quotes prevents expansionSingle quotes () inhibit all expansion$echo *** SALE ***`Double quotes() inhibit all expansion except :$ (dollar sign variable expansion (backquotes), command substitution\ (backslash), single character inhibition! (exclamation point), history substitutionDouble quotes inhibit file name generation expansion, but not other types.

    *

    (C) Mustafa Golam, 2007

  • Use the up and down arrow keys to scroll through previous commands.Type to search for a command in command history.{reverse-i-search)`:To recall last argument from pervious command:, (the escape key followed by a period) (hold down the alt key while pressing the period)You can ignore repeated duplicate commands and repeated lines that only differ in pre-pended spaces by adding the following in your .bashrcexport HISTCONTROL=ignoreboth*

    (C) Mustafa Golam, 2007

  • moves to beginning of line.moves to the end of line.deletes to beginning of linedeletes to end of line.moves left or right by word.* Inherited from emacs. *

    (C) Mustafa Golam, 2007

  • By default, bash uses emacs-style keybindings for command editing.Type set o vi to change keybinding to vi-style.Make vi the default by adding the command above to $HOME/.inputrc*

    (C) Mustafa Golam, 2007

  • Applications/System Tools/TerminalGraphical terminal emulator with support for maintaining multiple tabbed shells simultaneously. Open a new tab Next/Prev tabCopy/Paste*

    (C) Mustafa Golam, 2007

  • Standard I/O and Pipes*

    (C) Mustafa Golam, 2007

  • Linux provides three I/O channels to processesStandard input keyboard is defaultStandard Output Terminal windows is defaultStandard Error Terminal window is default.Error messages could be saved in a file with the normal output going to the monitor.0,1,2 are called file descriptor.*

    (C) Mustafa Golam, 2007

  • Standard Input, Output, and Error can be reconnected to alternate locations.Shell redirection operators allow standard I/O channels to be redirected to/from a file.Pipes allow standard I/O channels to connected to the input or output of programs.Although it is also possible to pipe standard error into a file using some fairly complex syntax, this is generally not done.*

    (C) Mustafa Golam, 2007

  • Redirecting> command > file Directs standard output of command to file>> command > file Appends standard output of command to file.< command < filecommand receives its input from file.2> command 2>fileError messages from command are directed to file.2>>command 2>>fileError messages from command are appended to file.

    Piping|command1 | command 2Pipes the standard output of command1 into the standard input of command2.

    *

    (C) Mustafa Golam, 2007

  • If the target file of file redirection with > already exists, the existing file will be overwritten.To append data to an existing file, use >> to redirect instead of >.Redirect standard output with >Example: redirect standard output to a file.Find /etc name passwd > findresult.Standard error is still displayed on the screen.*

    (C) Mustafa Golam, 2007

  • Redirect Standard Error with 2>Example: redirect standard error to a file:find /etc name passwd 2> finderrorsStandard output is displayed on the screen.Redirecting further standard error, appending to the same file, with 2>>.

    *

    (C) Mustafa Golam, 2007

  • Redirection of Standard Output and Standard Error can be performed simultaneously.find / -name passwd 2> errs > resultsEach I/O Channel can be redirected to different files, or to the same file:find / -name passwd > alloutput 2>&1(or) find / -name passwd &> alloutput*

    (C) Mustafa Golam, 2007

  • Redirecting Standard Input with and >& operators.set o viuse vi syntax on bash command line instead of default emacs syntax.For a complete list of set values, see the set command under the SHELL BUILTIN COMMANDS section of the bash man page. Also in this section is a list of items configurable through the shopt command.

    *

    (C) Mustafa Golam, 2007

  • Shell variables exit only in current shell instance.Environment variables passed to subshells.Shell variables can be exported into environmentEDITOR=/usr/bin/vim; export EDITORExport EDITOR=/usr/bin/picoTo blank the value of an environment variable, use the unset built-in command.$unset EDITOR*

    (C) Mustafa Golam, 2007

  • HOMEPath to users home directoryLANGIdentification of default language programs should use; example: en_US.UTF-8 for U.S. English.PWDUsers current working directory.EDITOR Default editor programs should invoke for text editing.LESSOptions to pass to the less command. The less command has many options; to force a set of options to always be used, set the LESS variable. For example: LESS=-emqsSHELLpath to loging shellUSERUsername of userDISPLAYX Display NameVISUALName of visual editor*

    (C) Mustafa Golam, 2007

  • TERMEnvironment variable setting the terminal type.resetCommand (not variable) used to reset a terminal should the screen become corrupted.If a terminal is improperly set, the computer will not be able to properly display data.For more complex adjustments to your terminal settings, set the stty command.The stty command can perform a number of terminal settings to your system.*

    (C) Mustafa Golam, 2007

  • PATHcolon separated list of locations where commands can be found.When a command is executed and the path is not specified, then the shell will look in these directories in the given order, stopping on first match, to find the command.whichcommand showing location in the PATH of an executable $which xterm$ /usr/bin/xtermExecutables location may be specified.$/bin/ls /etc./myls/etcUse the built-in shell type command to ask the shell what is using to fulfill the following commands.*

    (C) Mustafa Golam, 2007

  • A simplification:Split the line into wordsFunction and alias expansionCurly brace string expansionTilde expansionParameter and variable expansionSplit the line into words againFile glob expansionFile redirectionRun the command!*

    (C) Mustafa Golam, 2007

  • Scripts of commands executed at loginUses include:Configure the shell by setting local variables or running the set and shopt commands.Configure other programs through environment variablesEstablish aliasesRun program on Startup.*

    (C) Mustafa Golam, 2007

  • Login shells are first shells started (i.e. when you log in)Shells launched from a login shell typically are not login shells.Login shells and non-login shells run different startup scripts.A login shell is a shell that someone started by login onto the system. A non-login shell is a shell started up in some other way, perhaps by a user or a program issuing the bash command.*

    (C) Mustafa Golam, 2007

  • Login Shells/etc/profile/etc/profile.d~/.bash_profile~/.bashrc/etc/bashrcNon-login Shells~/.bashrc/etc/bashrc/etc/profile.dTypical sorts of commands placed in startup scripts include:Local variable settings, particularly PS1Environment variable settings, such as PATH or LESS.Aliases, or perhaps unalias to remove undesired aliases set globally in earlier scripts.A umask can be setted.*

    (C) Mustafa Golam, 2007

  • System-wide startup script for login shells.Parsed by all users with Bourne-style shells, including bash and sh.Usually sets default PATH variable, user limits, and other variables and settings.Bash only sources /etc/profile if the shell is a login shell.This script will set a series of variables including PATH, USER, LOGNAME, MAIL, HOSTNAME, HISTSIZE and INPUTRC.It will also run scripts in the /etc/profile.d directory.*

    (C) Mustafa Golam, 2007

  • Some application-specific startup scripts in this directory.Scripts called by a for-loop in /etc/profileScripts set up variables and run initialization procedures.Two copies of each script are listed in this directory, a Bourne Shell style with a .sh suffix, and a C shell style with a .csh suffix.*

    (C) Mustafa Golam, 2007

  • For user-specific settingsCommon to place variable settings, aliasesCommands that place output to the screen, such as the date command, should go in .bash_profile, not .bashrc.The ~/.bash_profile file is only called by login shells.Never put any command that may echo something to the screen in the ~/.bashrc file; such command belong in the ~/.bash_profile file only.*

    (C) Mustafa Golam, 2007

  • Resides in home directoryExecuted when exiting a login shell.Useful for running programs automatically at logoutExample uses:Make backup of filesDelete temporary filesDisplay Date and time of logout.*

    (C) Mustafa Golam, 2007

  • Detected by the kernel as SCSI devices./dev/sdaXAutomatically mounted in GNOME/KDE.Icon created in Computer windowMounted under /media/Device ID is build into device by vendor.Most vendors give USB disks a label. fstab-sync reads that label and automatically puts an entry in the /etc/fstab for it, mounting it in /media/Like other disks, you can use fdisk and mke2fs to create partitions and filesystems on USB disks.*

    (C) Mustafa Golam, 2007

  • Must be manually mounted and unmounted mount /media/floppyumount /media/floppyDOS floppies can be accessed with mtools.mount and unmounts device transparently.Uses DOS naming conventions.mdir a:mcopy /home/file.txt a:For a complete list of the mtools commands, run mtools and/or consult the mtools info page.*

    (C) Mustafa Golam, 2007

  • Two types of format needed to prepare a floppy:A low level format (rarely needed)$fdformat /dev/fd0H1440A filesystem, one of :$mkfs t ext2 /dev/fd0$mke2fs/dev/fd0$mkfs t vfat /dev/fd0mformat a:Only the superuser or a non-privileged user logged into the system console can run these commands. Others do not have permission to do this.

    *

    (C) Mustafa Golam, 2007

  • Archiving places many files into one target file.Easier to backup, store and transfer.tar standard Linux archiving command.Originally, tar was used to create archieves on tap devices, hence its name- which stand for tape achieve.*

    (C) Mustafa Golam, 2007

  • Syntax:tar cvf archive_name filesc creates a new archive.vproduces verbose messages.Farchive_name is the name of the new file.

    *

    (C) Mustafa Golam, 2007

  • Syntax:tar tfarchive_name.tartar tvfarchive_name.tarFirst form displays a list of all files in the archive.The v causes a long listing (like ls l) of each file in the archive.*

    (C) Mustafa Golam, 2007

  • Syntaxtar xvf archive_name.tarThe archive will be extracted in the current directory.Change to the target directory first.Files maintain their hierarchy relative to the current directory.

    *

    (C) Mustafa Golam, 2007

  • Results in smaller file sizeText files can be compressed over 75%Binary files usually dont compress much, if any.tar archives are often compressed.When text files often have patterns that lead to compression ratios of up to 75%, binary files rarely compress well with 0-25% being, typical.In fact, it is possible for a compressed binary file to actually be larger than the original.*

    (C) Mustafa Golam, 2007

  • gzip, gunzipStandard Linux compression utilityUp to 75% compression for text files.bzip2, bunzip2Newer Linux compression utility.Generally achieves better compression than gzip.The gunzip command can also uncompress files, compressed with the traditional Unix compress command, making compress essentially obsolete.zipCompatible with DOS/Windows PKzip/Winzip utilites and can compress more than one file into a single file.*

    (C) Mustafa Golam, 2007

  • The traditional compress command can reduces the text file by more than half. The Standard gzip command does a better job, reducing the file to less than 1/3 of the original size. Finally, the newer bzip2 command reduces the file to /14 of the original file.The c option to the gzip command leaves the original compressed file alone, but sends and uncompressed copy of the file to standard output. The d option decompresses a file, making gzip d file.gz equivalent to gunzip file.gz*

    (C) Mustafa Golam, 2007

  • Often tar archives are compressedtar can compress/uncompress archives.Compression switches- use during creation and extractionz for gzip compressionj for bzip2 compression.*

    (C) Mustafa Golam, 2007

  • Floppies can be used like tape drivesLow level format requiedFile system not neededUse tar to write to the floppy./dev/fd0 is the destinationFloppy cannot be mountedExample:tar czvf /dev/fd0 mydir*

    (C) Mustafa Golam, 2007

  • Advanced Topics in Users, Groups, and Permissions*

    (C) Mustafa Golam, 2007

  • User names map to user ID numbers.Group names map to group ID numbers.Data Stored on the hard disk is stored numerically.The user name and group affiliation of the file are not stored; rather, the user ID number and the group ID number are stored.*

    (C) Mustafa Golam, 2007

  • Authentication information is stored in plain is stored in plain text files:/etc/passwd/etc/shadow/etc/group/etc/gshadowThe /etc/passwd file contains seven fields: user name, password placeholder (for historical reasons), uid number, gid number of the users primary group, GECOS filed (usually containing the users real name), home directory, and shell to be run when the user logs in.The /etc/group file contains four fields: group password placeholder, gid number, and a comma separated list of group members.The /etc/shadow file is referenced when someone logs in: the file contains a mapping of a user name to a password.For a complete list of fields, see the man page$man 5 shadow*

    (C) Mustafa Golam, 2007

  • Server programs such as web or print servers typically run as unprivileged users, not as root.Examples: daemon, mail , lp, nobody.Running programs in this way limits the amount of damage any single program can do the system.These accounts exist primarily so that server programs can run as non-privileged users or as particular groups.*

    (C) Mustafa Golam, 2007

  • To change your password, run passwdInsecure passwords are rejected.To start a new shell as a different user:susu su usernamesu - username*

    (C) Mustafa Golam, 2007

  • Find out who you arewhoamiFind out what groups you belong togroups, idFind out who is logged inusers, who, wLogin/reboot historylast*

    (C) Mustafa Golam, 2007

  • Default permission for files is 666Default permission for directories is 777umask is subtracted from default to determine new file/directory permissions.Non-privileged users umask is 002Files will have permission of 664.Directories will have permission of 775.Roots umask is 022.Executive privilege is always denied a newly-create file, regardless of the umask in effect. Execute privilege always has to be explicitly granted to a file. Execute permission is given to a directory upon creation, unless explicitly denied by the umask.*

    (C) Mustafa Golam, 2007

  • Special permissions: a fourth permission set (in addition to user/group/other)Applicable in four cases:suid for an executable (4)sgid for an executable (2)sgid for a directory (2)sticky bit for all directory (1)Set with chmod or Nautilus.chmod 3775 groupdir

    *

    (C) Mustafa Golam, 2007

  • Special Permission for Executables:suid: Command run with permission of the owner of the command, not the executor of the command. Like passwd.sgid:command runs with group affiliation of the group of the command.In a long listing, the suid permission is displayed as a lower case s where the x would otherwise be located for the user permission (an upper case S would be present if the underlying executable permission is not set.)Commands running with the sgid permission run with the group affiliation of the group of the command.*

    (C) Mustafa Golam, 2007

  • Special permissions for directories:Sticky bit: files in directories with the sticky bit set can only be removed by the owner and root, regardless of the write permissions of the directory.Sgid :files created in directories with the sgid bit set have group affiliations of the group of the directory.*

    (C) Mustafa Golam, 2007

  • The sticky bit for a directory sets a special restriction on deletion of files: with the sticky bit set, only the owner of the file, and the superuser, can delete files within the directory. The sgid permission for a directory means that files created in the directory will inherit its group affiliation from the directory, rather than inheiriting it from the user.Often both the sticky bit and the sgid permission will be set on a group directory.*

    (C) Mustafa Golam, 2007

  • RHEL Power Tools*

    (C) Mustafa Golam, 2007

  • Introduction to String Processing*

    (C) Mustafa Golam, 2007

  • Displays first few lines (default: 10 lines) of the text in a file.$head /tmp/output.txtUse n or --lines displayed $head n 20 /tmp/output.txt*

    (C) Mustafa Golam, 2007

  • Displays last few lines (default: 10 lines) of text in a file$tail /etc/passwdUse n or -lines to change number of lines displayed.$tail n 5 /etc/passwdtail is often used by the system administrator to read the most recent entries in the log files.Use -f to follow the end of a text file as it changes.$tail f make.outUsed to watch log files.*

    (C) Mustafa Golam, 2007

  • word count also counts lines and characters$wc story.txtUse l for only line countUse w for only word countUse c for only character count*

    (C) Mustafa Golam, 2007

  • Sorts text to stout original file unchanged$ sort [options] filesCommon options-rReverses sort to sort descending-nNumeric sort-fignore (fold) case of characters in strings.-uunique (remove duplicate lines in output).-t x use x as field separator.-k POS1 sort from field POS1-k POS1.POS2 Sort using fields POS1 ending at POS2.The argument to the k can be two numbers separated by a dot. In this case, the number before the dot is the field number and the number after the dot is the character within that field with which to begin the sort.*

    (C) Mustafa Golam, 2007

  • Removes successive, duplicate lines in a file.Can use in conjunction with sort to remove all duplicates ( or use sort u)Use c to count number of occurrences of duplicate data.To print only unique line occurrence in a file (removing all duplicate lines), input to uniq must first be sorted.Since uniq can be given fields or columns on which to base its decisions, these are the fields or columns upon which its input must be sorted.*

    (C) Mustafa Golam, 2007

  • Use u to output only the lines that are truly unique only occurring once in the input.Use d to output only print one copy of the lies that are repeated in the input.Use c to produce a frequency listing. Each line will be prepended with a number indicating how many times it appears in the input.Use fn or -sn to avoid comparing the first n fields or characters in each line respectively.$cut d: -f7 /etc/passwd | sort | uniq*

    (C) Mustafa Golam, 2007

  • Display specific columns of file data$cut f4 results.data-fspecifies field or column-d specifies field delimiter (default is TAB)$cut f3 d: /etc/passwd-c cuts by characters$cut c2-5 /user/share/dict/words*

    (C) Mustafa Golam, 2007

  • paste paste files togethertr character translatorpaste combines files horizontally. It takes a line from each file and pastes them together to standard output, separated by a tab. Use d option to change the output of the output delimeter.$paste d: ids.txt data.txt > merged.txttr is used to translate characters; that is, given two ranges of characters, any time a character in range 1 is found, it is translated into the equivalent character in range 2. This command is commonly used in shell scripts to ensure that data is in an expected case.*

    (C) Mustafa Golam, 2007

  • Compares two files for differences$diff area.c /tmp/area.c33c33< x = y +2;----> x = y+4;33c33 indicates line where files differ< indicates line in first file.> indicates line in second file.*

    (C) Mustafa Golam, 2007

  • Interactive spell-checkerEasy way to check spelling in a file.$aspell check letter.txtCan create personal dictionarylook quick spell check.$look must$aspell l will non-interactively list the misspelled words in a file read from standard input.Visit http://aspell.sourceforge.net*

    (C) Mustafa Golam, 2007

  • expand expand tabs into spacesfmt - reformat text into paragraph.fmt formats its input paragraphs of the line width you specify with wn. You can also request uniform spacing (with two spaces after each sentence) with u. fmt interprets blank line in its input as paragraph delimiters.pr -reformat text for printingBy default, it outputs 66-line pages including 56 lines of text and a header (which can be suppressed)$ pr f /usr/share/dict/words | lpr

    *

    (C) Mustafa Golam, 2007

  • Advanced!More advanced.Simple*

    (C) Mustafa Golam, 2007

  • Advanced Uses of the vi and vim Editors*

    (C) Mustafa Golam, 2007

  • Ggo to last line in the file1Ggo to first line in file (any number can be given and curser will jump to that line) go forward one full screengo back one full screengo down half a screengo up half a screenThis is useful when an error message tells you that an error exists on the particular line of a file. You can use the G command preceded by that number to jump right to the offending line.*

    (C) Mustafa Golam, 2007

  • Hgo to first line on screen(high)Mgo to middle line on screen (middle)Lgo to last line on screen(low)z Make current line first line on screen.z-make current line last line on screen.*

    (C) Mustafa Golam, 2007

  • The output of a command can be placed in the file.The data in the file can be used as input of a command.Examples:!!dateReplace current line with the output of date command.!}sortThe paragraph will then be replaced with the output of the sort command.!}fmt -66Will replace the paragraph with a paragraph formatted to be less than 66 characters wide.

    *

    (C) Mustafa Golam, 2007

  • sed style search and replaceDifferent default addressing rule.No addresscurrent line only.1,12Change lines 1 through 121,$ or %for changes in the entire file..,.+10from current line(.) to current line plus 10 lines (.+10)Example: :%s/Ohiho/Iowa/g :%s/dev/had /dev/sdag :%s/\/dev\/had/\/dev/\sda/g*

    (C) Mustafa Golam, 2007

  • Allow selection of blocks of textvcharacter-oriented highlightingVline-orienting highlighting block orienting highlightingVisual Keys can be used in conjunction with movement keys: w, ), }, arrows, etc.Highlighted text can be deleted, yanked, changed, filtered, search/replaced, etc.cchangeddeletey yank(copy)gg format to textwidth columns> indent>zfile:notherfile:n!otherfile:n#*

    (C) Mustafa Golam, 2007

  • Configuring on the fly:set or :set allConfigure permanetly~/.vimrc or ~/.exrcA few common configuration items:set showmatch or :se sm or :se nosm:set autoindent or :se ai or :se noai:set textwidth=65 (vim only) :set wrapmargin=15 :set wrapmargin=0:se wm=15 and :se wm=0:set ignorecare or :se ic or :se noic:set number or :se nu or :se nonu

    *

    (C) Mustafa Golam, 2007

  • Learn more cursor movementsExpanding change, delete, yank, and put vocabularyAdd the advanced material from the appendix to your skill base.Learn more configuration features.Play with filters.:help*

    (C) Mustafa Golam, 2007

  • 0start of current line$ end of current line^first nonblank character of current line.e end of next wordgg top of current filen% go to a line n percent through the current filen|go to column n of the current lineRead the material in :help. Learn to maneuver around the online help. Place the cursor over one of the |tags| and go to that with keystroke, returning to the previous screen with :n#. This is a rich resource well worth being mined extensively.*

    (C) Mustafa Golam, 2007

  • String Processing with Regular Expressions*

    (C) Mustafa Golam, 2007

  • Regular expressions are a pattern matching engineUsed by many tools, including: grep, sed, less , vi, awkValues:Power over ease of useGreed!Two types: BasicExtended*

    (C) Mustafa Golam, 2007

  • grep : the general regular expression processor, which analyzes the contents of files a line at a time, returning line that match a pattern.Sed: the stream editor, returns the contents of a file (or stream of data), performing a specified search and replace instruction.less: which uses regular expression in search commands.vi: which uses regular expression for searches (like less) or search and replace (like sed).awk : a data oriented programming language.*

    (C) Mustafa Golam, 2007

  • Prints lines of files where a pattern is matched$grep gmustafa /etc/passwdAlso used as filter in pipelines.$ls | grep .cUses regular expressions$grep [0-9][A-Z]\{3\}[0-9]\{3\} cars*

    (C) Mustafa Golam, 2007

  • -vreturn lines that do not contain pattern-n precede returned lines with line numbers.-conly return a count of line with the matching pattern.-l only return the names of the files that have at least one line containing the pattern.-r perform a recursive search of files, starting with the named directory.-iperform a case-sensitive search.*

    (C) Mustafa Golam, 2007

  • Must edit and install your cron table fileCron table file cannot be edited directlyEdit the file and then install with crontab orEdit the file through crontabSyntax:contab [-u user] filecrontab [-l|-r|-e]Cron table files( crontabs ) are stored in /var/spool/cron, which is not accessible by non-privileged users.

    *

    (C) Mustafa Golam, 2007

  • Quote search and replace instructionsSed addresses$ sed s/dog/cat/gpets$ sed 1,50s/dog/cat/g pets$ sed /digby/,/duncan/s/dog/cat/g petsMultiple sed instructions$ sed e s/dog/cat/ e /s/hi/lo pets$ sed f myedits pets*

    (C) Mustafa Golam, 2007

  • Finding and processing Files*

    (C) Mustafa Golam, 2007

  • $ find [directory] [criteria]Searches directory trees in real-timeSlower but more accurate than slocateCWD is used if no starting directory givenAll files are matched if no criteria given.Can execute commands on found filesMay only search directories where the user has read and execute permission.Find has a huge amount of options that can be provided to describe exactly what kind of file should be found.You can search bases on file name, file size, last modified time stamp, inode number, and many, many more.find allows you to perform arbitrary actions on arbitrary files.*

    (C) Mustafa Golam, 2007

  • $ find name show.pngSearch for files named show.png$find / -name *.png$find -iname show.pngCase-insensitive search for files named show.png, Snow.png, SNOW.PNG, etc.$find user gmustafa group gmustafaSearch for files owned by the user gmustafa and the group gmustafaThe regex option in find does not work quite the way one would expect. regex applies the regular expression to the name of the file, including the absolute path to the file.*

    (C) Mustafa Golam, 2007

  • Criteria and ANDed together by default.Can be ORd or negated with o and notParentheses can be used to determine logic order, but must be escaped in bash.$ find user gmustafa not group root$ find -user gmustafa o user root$ find not\(-user gmustafa o user root \)$ find / -name *.png user gmustafa mtime+12$ find / -name *.png not user abcdLogical ANDs have a higher priority than a logical OR, and a logical NOT has a higher priority than an AND or an OR.To force precedence of an expression, you can enclose options that should be grouped together in parentheses.*

    (C) Mustafa Golam, 2007

  • Can match ownership by name or id (-user, -group, -uid, -gid)$ find / -owner gmustafa gid 500Can match octal or symbolic permissions$ find perm 755# if anyone can write$ find perm +2#if anyone can write$ find perm -2#if everyone can write$ find perm +o+w# if other can writeUse not to test denied permissions.A numeric permission preceded by will match files that have at least one bit (user, group or other) for that permission set.Symbolic permission by a + will match any file where all criteria are met.To match files where someone has been denied a permission, simply write a search for files where the permission is granted and then negate it. In other words, to find files where neither the user nor the group have read access you could use something like: find not perm +ug+r

    *

    (C) Mustafa Golam, 2007

  • Many find criteria take numeric values $ find size 10MFiles with a size of exactly 10 Megabytes.$ find size +10MFiles with a size over 10 Megabytes$ find -size -10MFiles with a size less than 10 Megabytes$ find / -atime 5The date of the last time the file was read (-atime)$ find / -mtime +5The date of the last change to the files data (-mtime)$ find / -ctime -5The date of the last changes to the files metadata. (-ctime)*

    (C) Mustafa Golam, 2007

  • $find name *.conf exec cp {} {}.orig \;Create backup copies of configuration files, adding a .orig extension$find /tmp ctime +3 user gmustafa ok rm {} \;Prompt to remove gmustafas tmp files over 3 days old.$find ~ -perm +2 exec chmod o-w {} \;Fix world-writable files in your home directory.If your exec command does not include {}, find will still execute the command once for each file that is found.*

    (C) Mustafa Golam, 2007

  • find can match by inode timestamps-atime : when file was last read-mtime : when file data last changed-ctime:when file metadata last changedValue given is in days$find mtime -10Files modified less than 10 days ago.*

    (C) Mustafa Golam, 2007

  • While the values passed to atime, -ctime and mtime are measured in days, there are also corresponding criteria that perform searches in minutes: -amin, -cmin and mmin.You can match access times relative to the timestamps of other files using -anewer, -cnewer and newer, which test mtimes.$ find newer recent_file.txtWould list all files with mtimes more recent that that of recent_file.txt.To match files older than recent_file.txt you would simply negate the mnewer criteria.$ find not newer recent_file.txtThe metadata, including all three timestamps, for a file can be manually examined using the stat command.*

    (C) Mustafa Golam, 2007

  • Commands can be executed on found files.Command must be proceeded with -exec or ok -ok prompts before acting on each file.Command must end with \;Can use {} as a filename placeholder$ find size +100M ok gzip {} \;-ok options, which caused find to ask for each file.When a character is prepended with a backslash (\), bash is instructed to treat it literally, so typing \; at bashs command prompt will send; to find after bash has done its interpretations.

    *

    (C) Mustafa Golam, 2007

  • Investigating and Managing processes*

    (C) Mustafa Golam, 2007

  • A process is an executing program which has many components and propertiesExec threadPIDPriorityMemory contextEnvironmentFile descriptorsSecurity credentials*

    (C) Mustafa Golam, 2007

  • Once process forks a child, pointing to the same pages of memory, and marking the area as read-only.Then the child execs the new command, causing a copy-on-write fault, thus copying to a new area of memory.A process can exec, without forkingThe child maintains the process ID of the parent.*

    (C) Mustafa Golam, 2007

  • init is the first process started at boot time always has PID 1Except init, every process has a parent.Processes can be both a parent and a child at the same time.pstree shows the process ancestry for all process running on the system.*

    (C) Mustafa Golam, 2007

  • A process can be on of the many states:-R Runnable (on the run queue) process in the run queue. It is waiting for its turn to run or it is executing.-SSleepingProcess is not executing, not it is ready to run. It is waiting for an event to occur or a signal to arrive to wake it up.-TstoppedProcess is not executing because it has been stopped.-DUninterruptible sleepProcess is sleeping and can not be woken up until an even occurs. It can be woken by a signal. Typically, the result of an I/O Operations.-Z Defunct (Zombie) processJust before a process dies, it sends a signal to its parent and waits for an acknowledgement before terminating. Even if the parent process does not immediately acknowledge the signal, all resources except for the process identity number (PID) are released. Zombie process are cleared from the system during the next system reboot and do not adversely affect system performance.*

    (C) Mustafa Golam, 2007

  • psDisplays processes informationSyntax:ps [options]Useful options:a Processes by all usersxprocess from all terminalu show process ownerw include command argumentsfshow process ancestry.The options described above are based on output conforming to the UNIX98 Standard.-llong listing. Includes more information such as the process owners UID.$ ps alx | grep lpd$ pgrep lpdThe above two command are identical.

    *

    (C) Mustafa Golam, 2007

  • Syntax:$ kill [-signal ] pid(s)$ kill [-signal] %jobIDSends the specific signal to a processDefult signal is TERM$kill l lists all available signals$killallRead man 7 signal.kill can send many signals, but processes only respond to the signals they have been programmed to recognize.Signals may be sent to processes interactively using top and gnome-system-monitor.

    *

    (C) Mustafa Golam, 2007

  • Most desirable way to end a process is to let it end normallyCommands finish, applications are exited.Can attempt to interrupt with (INT) or send a TERM signalIf all else fails, send a KILL signal.Using KILL signals on a route basis may cause zombie process and lost data.*

    (C) Mustafa Golam, 2007

  • Display real-time process informationAllow sorting, killing and renicingCommand-line: topGUI: gnome-system-monitorRead: man top and help of gnome-system-monitor*

    (C) Mustafa Golam, 2007

  • When a command is entered, the shell will not process further input until the process is complete and the shell prompt is redisplayed. i.e. job control.The typeahead buffer allows you to type other command, but they will not be processed until the pending process completes, or returns.*

    (C) Mustafa Golam, 2007

  • At process invocation timeSyntax:$ nice [-n adjustment] commandProcesses are scheduled with a Defult priority of 0Priority value can range from -20 (highest priority) to 19 (lowest).$ nice myprog$ nice n 15 myprogNon-privileged users may not set niceness value to less than zero; that is , they may not request a higher than normal priority for their processes. This is a function reserved for the superuser.*

    (C) Mustafa Golam, 2007

  • renice changes the priority of a running process.$ renice # [ [ -p | g] PID] [[-u]user]# is the priority value.Once a priority value is raised, a non-privileged user can not lower it.$ renice 15 p < PID of users offending, greedy process>$ renice -15 p The p options is not necessary. If you wish to change the priority of an entire process group, use the g option.Use u option, to modify the priority of all the process of a particular user.$ renice 15 u gmustafa*

    (C) Mustafa Golam, 2007

  • Running a command in the background allows another process to run concurrently on the same terminal.Launch a program as a background process by appending an ampersand (&) to the end of a command:$firefox &When a process is started in the background, a new bash sub-shell is created. The bash program is then replaced with the command being executed (the fork then exec procedure). Background processes can be managed like any other process.*

    (C) Mustafa Golam, 2007

  • Foreground jobs can be suspended: temporarily halted without being killedSuspend a foreground process with Suspended jobs can be:Resumed in the background (bg)Resumed in the foreground (fg)When the job resumes, it will continue executing from the point at which it was suspended, it will not have to start over from the beginning.*

    (C) Mustafa Golam, 2007

  • jobs displays all process running in the background or that suspended.The number in brackets is a job number, used to kill jobs or bring them back to the foreground.Job numbers are referenced with %.*

    (C) Mustafa Golam, 2007

  • When a command is suspended or backgrounded, it can be brought back to the foreground with fg.Suspended jobs can be resumed in the background with bg.Syntax:$ fg[%job_number]$ bg[%job_number]

    *

    (C) Mustafa Golam, 2007

  • List of commands separated by semi-colonsList inside () to run inside a subshell $ (cd /usr; du ) &A subshell group will combine the commands so they are treated them as one unit.When a group of commands is placed inside parentheses, a new subshell is spawned and output can be redirected as if it were one command.$ (date; who | wc l) >> logfile*

    (C) Mustafa Golam, 2007

  • Syntax:$ at time

    $ atq [user]$ atrm [user|atJobID]Commands will be executed at the time indicatedNon-redirected output is mailed to the user.$ at 8:00pm December 7$ at 7 am Thursday$ at now + 5 minutes$ at midnight +23 minutes*

    (C) Mustafa Golam, 2007

  • The cron mechanism allows processes to be invoked periodicallyUser need not to be logged onCron jobs are listed in a crontab fileThe cron mechanism is controlled by a daemon called crond. This daemon wakes up every minute or so and determines if any entry users cron tables need to be executed. If the time passed for an entry to be started, it is started. A cron job can be scheduled as often as once a minute or as infrequently as once a year.*

    (C) Mustafa Golam, 2007

  • Must edit and install your cron table fileCron table file cannot be edited directlyEdit the file and the install with crontabOrEdit the file through crontabSyntax$ crontab [-u user] file$ crontab [-l | -r | -e]*

    (C) Mustafa Golam, 2007

  • Entry consists of five space delimited field followed by a command lineOne entry per line, no limit to the line length.Fields are minute, hour, day of month, month, and day of week.Comment line begin with #

    *

    (C) Mustafa Golam, 2007

  • Network Clients*

    (C) Mustafa Golam, 2007

  • EpiphanyUses same rendering engine as FirefoxFully Gnome-complaint, but fewer features.KonquerorKDE web browser/file managerSupports tabs, popup-blocking, etc.Uses khtml rendering engine.

    *

    (C) Mustafa Golam, 2007

  • linksProvided by the elinks rpmFull support from frames and sslExamples$ links http://www.redhat.com$ links dump http://www.redhat.com$ links source http://www.redhat.com

    *

    (C) Mustafa Golam, 2007

  • Retrieves files via HTTP and FTPNon-interactive useful in shell scripts.Can follow links and traverse directly trees on the remote server useful for mirroring web and FTP sites.Read info wget and wget help.*

    (C) Mustafa Golam, 2007

  • ssh/scptelnet and the r servicesrsync FTP clientsNautilus *

    (C) Mustafa Golam, 2007

  • Public-key encryption technology replacement for various unsecured services.Allows secure access to remote systems$ ssh gmustafa@oss2 -or-$ ssh -l gmustafa oss2gmustafa@oss2s password:$ ssh oss2 ls /tmp$ ssh oss1 df -h*

    (C) Mustafa Golam, 2007

  • Secure replacement for rcpLayered on top of ssh$ scp source destinationRemote files can be specified using:user@host:/path/to/file-roptoin enables recursion-ppreserves time and permissions-ccompresses datastreamAlso available is sftp, an interactive file-transfer program similar to a simple ftp client. The remote hosts sshd needs to have support for sftp in order for the sftp client to work.scp requires that the destination be a directory if the source is a directory or consists of more than one file.*

    (C) Mustafa Golam, 2007

  • Insecure protocols mostly replaced by sshtelnet : login names and password pass over the network in clear textr services (rsh, rlogin, rcp): generally insecure authentication mechanism.telnet client can be used to connect to services running on arbitrary portsExamples: testing your mail server$ telnet localhost 25These tools should never be used.*

    (C) Mustafa Golam, 2007

  • A drop-in replacement for rcp copying to or from remote systems.Can use ssh for transport$ rsync e ssh mysong.mp2 172.27.12.13:/home/gmustafaFaster than scp copies difference in like files.Useful options to rsync-eUse an external, rsh-compatible program to connect (usually ssh)-aRecurse subdirectories, preserving permissions, ownership, etc.-rRecurse subdirectories without preserving permissions, etc.--partialcontinue partially downloaded files--progressprint a progress bar while transferring-pSame as partial progressRead man 1 rsync*

    (C) Mustafa Golam, 2007

  • Versatile command line FTP clientAnonymous or real-user sessions$ lftp ftp.cdrom.com$ lftp u gmustafa ftp.myserver.comAutomated transfer with non-interactive lftpgetGraphical tools gftp.*

    (C) Mustafa Golam, 2007

  • Applications/Internet/gFTPGraphical FTP ClientAllows Drag-and-Drop transfersAnonymous or Authenticated accessOptional secure transfer via ssh (sftp).*

    (C) Mustafa Golam, 2007

  • FTP-like client to access SMB/CIFS resourcesExamples:View shares on a server$smbclient L server1Access a share$smbclient U student //server1/homesCIFS is most commonly implemented as Microsoft Windows Network Neighborhood.Useful options include:-wworkgroup or domain-U Username-NSuppress password prompt (otherwise you will be asked for a password).*

    (C) Mustafa Golam, 2007

  • pingDetects if it is possible to communicate with another system. Many systems no longer respond to pings.tracrouteDisplays the computers through which a packet must pass to reach another system.mrt The mtr command is a repetitive version of traceroute, giving continually updated connection time statistics.hostPerforms hostname to IP address translation, as well as the reverse.digPerforms a service similar to host in greater datail.netstatProvides a service similar to host in greater detail.gnome-nettool (GUI)A graphical front end of tools listed above (as well as some others) in a single, simple interface. gnome-nettool can be run from the command line or by selecting its icon from the internet section of the Application Menu. Note that, this tool may no be installed by default.*

    (C) Mustafa Golam, 2007

  • Bash Shell Scripting*

    (C) Mustafa Golam, 2007

  • Shell scripts are text files that contains a series of commands or statements to be executed.Shell scripts are useful for:Automating commonly used commands.Performing system administration and troubleshootingCreating simple applicationsManipulations of text or files.Application prototyping*

    (C) Mustafa Golam, 2007

  • Step 1: Use a text editor such as vi to create a text file containing commnds.First line contains the magic shbang sequence : #!#!/bin/bashComment your scriptsComments start with a #Create shell script which is self documenting.If you enter this by pressing \ key followed by the Enter key on the most keyboards. This will enable you to enter one command that spans multiple lines.*

    (C) Mustafa Golam, 2007

  • Step 2: Make the script executable$ chmod a+x myscript.shTo execute the new script:Place the script file in a directory in the executable path OR-Specify the absolute path or relative path to the script on the command line.*

    (C) Mustafa Golam, 2007

  • Use echo to generate simple output$ echo Welcome to Redhat Linux paradise!$ echo n please enter the file name: Use printf to generate formatted output.$ printf the result is %0.2f\n $RESULTSyntax similar to C printf() functionDoes not automatically put a newline at the end of the output.*

    (C) Mustafa Golam, 2007

  • Use read to assign an input value to a shell variable:echo n Enter the filename: read FILENAMEread reads from standard input and assigns one word to each variable.Any leftover words are assigned to the last variable.A word is defined as a character string surrounding with white space such as spaces and tabs. Can be changed by IFS. IFS=:If there are more words than variables, the last variable is assigned all the remaining words.*

    (C) Mustafa Golam, 2007

  • #!/bin/bashecho n Enter name (First Last):read FIRST LASTprintf Your First name is %s and your last name is %s \n \ $FIRST $LASTThe (-p) option is used to display a prompt string. Place quotes around the string if you need to prompt the user with a multiple-word command#!/bin/bashread p Enter Several Values: value1 value2 value3echo value 1 is $value1echo value 2 is $value2echo value 3 is $value3

    *

    (C) Mustafa Golam, 2007

  • Commands exit with an exit status0 for success, 1 to 255 for failureExit status of most recently executed command is kept in the $? Variable just like return values form shell functions.Shell scripts may set an exit status with the exit command.exit 1 # indicated an error*

    (C) Mustafa Golam, 2007

  • The three types in shell programming:Sequential structures the program flows one line after anotherSelection structures code execution based on a logical decision.if, if/else, if/elif/else and conditional operators.Repetition structures (loops) code execution is repeated based on a logical decisionfor, while and until

    *

    (C) Mustafa Golam, 2007

  • Commands may be executed conditionally, based on the exit stats of the previous command.&&logical AND||logical ORExamples:$ grep gmustafa passwd || echo No gmustafa!$ cp a /tmp/*.o . && echo Done!This structures can be used in the command line as well.*

    (C) Mustafa Golam, 2007

  • if selection structures execute the body of the structure only if the condition tested is true.if [condition]; thendo somethingfi

    *

    (C) Mustafa Golam, 2007

  • File tests:-f tests to see if file exist and is a regular file-d tests to see if a file exists and is a directory-x tests to see if a file exits and is executable if [-f $HOME/lib/functions ]; thensource ~/lib/functions fi

    *

    (C) Mustafa Golam, 2007

  • -d FILETrue if file is a directory-e FILETrue if file exists.-f FILETrue if file exits and is a regular file-h FILETrue if file is a symbolic link.-L FILETrue if file is a symbolic link.-r FILETrue if the file is readable by you.-s FILETrue if file exists and is not empty.-w FILETrue if the file is writable to you.-x FILETrue if the file is executable by you.-O FILETrue if the file is effectively owned by you.-G FILETrue if the file is effectively owned by your group.Type help test at the shell to see a complete list.*

    (C) Mustafa Golam, 2007

  • Strings may be tested as well-z returns true if the string is empty-nreturns true if the string is not empty.Operators such as =, !=, < and > may be used to compare strings as well.if [ $(id u) =0]; thenecho You are logged in as root fi

    *

    (C) Mustafa Golam, 2007

  • -z STRINGTrue if string is empty.-n STRINGTrue if string is not empty.STRING1=STRING2True if the strings are equal.STRING1!=STRING2True if the strings are not equal.STRING1STRING2True if STRING1 sorts after STRING2 lexicographically.-o OPTIONTrue if the shell option OPTIOIN is enabled.! EXPRTrue if EXPR is false.EXPR1 a EXPR2True if both EXPR1 AND EXPR2 is true.EXPR1 o EXPR2True if either EXPR1 OR EXPR2 is true.ARG1 OP ARG2Arithmetic tests. OP is one of the eq, -ne, -lt, -le, -gt, or ge.*

    (C) Mustafa Golam, 2007

  • if/else selection structures execute the body of the if structure only if the condition tested is true, otherwise the else is executed.if [ condition] ; thenDo somethingelseDo something elsefi*

    (C) Mustafa Golam, 2007

  • The case statement provides an alternative method for performing selections that may be cleaner than multiple if/elif/else tests.case variable inpattern1)do something ;;pattern2)do another thing ;;esac*

    (C) Mustafa Golam, 2007

  • The for repetition structure provides a method for iterating, or looping, through a list of values and executing commands on each of these values.for variable in list-of-valuesdocommands done*

    (C) Mustafa Golam, 2007

  • For loops are useful for iterating through numeric sequencesUse bash notation for simple sequencesfor I in {0..10}Will use : 0,1,2,3,4,5,6,7,8,9,10Use seq command for arbitrary incrementsFor I in $(seq 0 2 10)Will count by twos: 0, 2, 4, 6, 8, 10

    *

    (C) Mustafa Golam, 2007

  • The while loop structure provides a useful method for performing a set of commands while a condition remains true. The syntax is:while conditiondocommandsdone While loops are known as sentinel repetition structures.An until loop works in exactly the same way, except that it continues to execute as long as the command following the until statement executes successfully; that is, it will stop the loop when the command succeeds.*

    (C) Mustafa Golam, 2007

  • While loops can be disrupted during executioncontinue stops the current execution of the loop and reexamines the initial condition, possibly restarting the loop.break stops the processing the loop entirely, jumping past the done statement.exit exits from the shell scripts entirelyYou may provide an exit status.Without an explicit exit status, the exit command will exit with at status of zero, indicating success.*

    (C) Mustafa Golam, 2007

  • Positional parameters are special variables that hold the command-line arguments to the script.The positional parameters are available are $1, $2, $3, etc. These are normally assigned to more meaningful variable names to improve clarity.$* holds all command-line arguments.The variable $0 is reserved and specifies the program name as it was executed on the command line. Variables above $9 require special handling and so they must be enclosed in curly braces, e.g. ${11}.All positional parameters are read only variables.*

    (C) Mustafa Golam, 2007

  • Bash expects space-delimited parametersCauses problem when parameters have spacesExample : script.sh arg 1 arg 2$* contains arg 1 arg 2Solution: for VAR; do ; doneAutomatically assigns VAR with $1, $2, etc..Handles spaces in parameters gracefully.VAR would be set to arg 1, then arg 2*

    (C) Mustafa Golam, 2007

  • Bash mis-interprets spaces in filenamesSpace treated as filename-delimiter by defaultmy file interpreted as two files: my and fileIFS environment variable can be used to specify an alternate (or no) delimiter.Always reset after changingOLD_IFS=$IFS#Backup old delimiterIFS=$(echo)#Set empty delimiter#Do StuffIFS=$OLD_IFS#Restore IFS*

    (C) Mustafa Golam, 2007

  • Shell scripts may include shell functions.Shell functions may improve program readability. They also help to remove repetitious code from the scripts.Shell functions must be declared before they are used.If there is a section of shell code that is trying to accomplish the same task and it is five or more lines long then it is good candidate for being put in a separate function. This is known as functional decomposition and will improve the program readability.If there are a piece of shell code that you are likely to use again then it is also good candidate for being put in a separate function. This is called code reuse.Shell functions must be declared in the shell script before they may be used. This can be done by including the function before it gets called in the script or by sourcing another shell script using the keyword source or the (.) operator.*

    (C) Mustafa Golam, 2007

  • Arguments may be passed to a shell function by using their own set of positional parameters ($1, $2 etc.)myFunction $filename The value of $filename will be available as $1 inside the body of myFunction.Functions may return the values by using the return keyword which sets the value of the special variable $?.local make the variables unavailable outside the function. This is called information hiding and is useful for keeping function compartmentalized. In addition it will prevent us from accidentally overwriting a global variables.Functions may return vales using the return keyword which sets the value of the special variable $?.*

    (C) Mustafa Golam, 2007

  • Scripts can be typed at the bash prompt.If/else/for/while statements cause extended promptCan also separate lines with semicolon (;)Define functions for code reuseStore common functions in ~/.bashrcBash built-in fc for long commandsDefault editor is vi or $EDITOR*

    (C) Mustafa Golam, 2007

  • In order to debug a shell script invoke the shell interpreter with debug options or change the shebang to include the debug options.$bash x script_name$bash v script_name#!/bin/bash x#!/bin/bash -v*

    (C) Mustafa Golam, 2007

  • Advanced Features of the vi and vim Editors*

    (C) Mustafa Golam, 2007

  • Special features of vimFile and screen repositioningSetting marks in textMapping complex commands to keystrokes (:map)Advanced read and save*

    (C) Mustafa Golam, 2007

  • vim -o fn1 fn2start with multiple windowsssplit file horizontallyvsplit file verticallynopen new window, new fileqquit out of a window[hjkl]move to different window.[+-]resize window:help windowsshow help for windows.*

    (C) Mustafa Golam, 2007

  • gq reformats text width.Usage:Make sure textwidth is set::set textwidth=65Issue the gq command followed by the paragraph indicator:gq}1GgqG*

    (C) Mustafa Golam, 2007

  • Recording keystrokes and playback.qc record keystrokes saving to buffer cqstop recording keystrokes@cplay back keystrokes from buffer cOther configuration options:syntax :nohl*

    (C) Mustafa Golam, 2007

  • Set a mark in text with a single quote followed by a letter of the alphabet specifying the mark name.Example: delete some linesMove the curson to the first line to deleteSet mark a: aMove the cursor to the last line to delete.Set mark b: bDelete from marks a to b: :a,bd*

    (C) Mustafa Golam, 2007

  • You can create your own commands with the :map commandPlace: map commands in ~/.vimrc or ~/.exrc fileExample: mapping to : syntax off: map : syntax off:map :syntax off:map :w!:!aspell check %:e!%The keystroke may not be entered into the file. To force it to be read, run before the : The forces the to be taken literally.The sequence , meaning carriage return should be entered just as shown, with the four separate characters.*

    (C) Mustafa Golam, 2007

  • Returns to your previous locationJJoin with the next file.~Change character case>>Indent
  • LUGs (bdlug)http://www.redhat.com/traininghttp://www.redhat.com/training/developter/courses/http://www.redhat.com/training/architect/courseshttp://www.redhat.com/training/developter/courses/http://www.idiom.com/free-compilershttp://www.redhat.com/apps/support/knowldedgebasehttp://www.tldp.orghttp://www.linuxquestions.org*

    (C) Mustafa Golam, 2007

  • It is worth working hard today to learn a thing and so be lazy tomorrow!!*

    (C) Mustafa Golam, 2007

    *