linux_rv

Upload: raazia-mir

Post on 07-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 linux_RV

    1/46

    TIP 1:All of these commandsshouldwork from your command prompt (regardless which shell you're using). If youneed help understanding what the options are, or how to use a command, try adding this to the end of yourcommand: --help

    For example, for better understanding of the df command's options, type:df --help

    mkdir - make directories

    Usage

    mkdir [OPTION] DIRECTORY

    Options

    Create the DIRECTORY(ies), if they do not already exist.

    Mandatory arguments to long options are mandatory for short options too.

    -m, mode=MODE set permission mode (as in chmod), not rwxrwxrwx - umask

    -p, parents no error if existing, make parent directories as needed

    -v, verbose print a message for each created directory

    -help display this help and exit

    -version output version information and exit

    cd - change directories

    Use cd to change directories. Type cd followed by the name of a directory to access that directory.Keep

    in mind that you are always in a directory and can navigate to directories hierarchically above or below.

    mv- change the name of a directory

    Type mv followed by the current name of a directory and the new name of the directory.

    Ex: mv testdir newnamedir

    pwd - print working directory

    will show you the full path to the directory you are currently in. This is very handy to use, especiallywhen performing some of the other commands on this page

    rmdir - Remove an existing directory

    rm -r

    Removes directories and files within the directories recursively.

    chown - change file owner and group

  • 8/6/2019 linux_RV

    2/46

    Usage

    chown [OPTION] OWNER[:[GROUP]] FILE

    chown [OPTION] :GROUP FILE

    chown [OPTION] --reference=RFILE FILE

    Options

    Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change theowner and group of each FILE to those of RFILE.

    -c, changes like verbose but report only when a change is made

    -dereference affect the referent of each symbolic link, rather than the symbolic link itself

    -h, no-dereference affect each symbolic link instead of any referenced file (useful only on systems that

    can change the ownership of a symlink)

    -from=CURRENT_OWNER:CURRENT_GROUP

    change the owner and/or group of each file only if its current owner and/or group match thosespecified here. Either may be omitted, in which case a match is not required for the omittedattribute.

    -no-preserve-root do not treat `/' specially (the default)-preserve-root fail to operate recursively on `/'-f, -silent, -quiet suppress most error messages-reference=RFILE use RFILE's owner and group rather than the specifying OWNER:GROUP values

    -R, -recursive operate on files and directories recursively-v, -verbose output a diagnostic for every file processedThe following options modify how a hierarchy is traversed when the -R option is also specified. If morethan one is specified, only the final one takes effect.-H if a command line argument is a symbolic link to a directory, traverse it-L traverse every symbolic link to a directory encountered-P do not traverse any symbolic links (default)chmod - change file access permissions

    Usage

    chmod [-r] permissions filenames

    r Change the permission on files that are in the subdirectories of the directory that you are currently inpermission Specifies the rights that are being granted. Below is the different rights that you can

    grant in an alpha numeric format.filenames File or directory that you are associating the rights withPermissionsu - User who owns the file.g - Group that owns the file.o - Other.a - All.r - Read the file.w - Write or edit the file.

  • 8/6/2019 linux_RV

    3/46

    x - Execute or run the file as a program.Numeric Permissions:CHMOD can also to attributed by using Numeric Permissions:400 read by owner040 read by group004 read by anybody (other)

    200 write by owner020 write by group002 write by anybody100 execute by owner010 execute by group001 execute by anybody

    ls - Short listing of directory contents

    -a list hidden files-d list the name of the current directory-F show directories with a trailing '/'

    executable files with a trailing '*'-g show group ownership of file in long listing

    -i print the inode number of each file-l long listing giving details about files and directories-R list all subdirectories encountered-t sort by time modified instead of name

    cp - Copy files

    cp myfile yourfile

    Copy the files "myfile" to the file "yourfile" in the current working directory. This command will createthe file "yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.

    cp -i myfile yourfile

    With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.

    cp -i /data/myfile

    Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt beforeoverwriting the file.

    cp -dpr srcdir destdir

    Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), fileattributes (-p option), and copy recursively (-r option).

    ln - Creates a symbolic link to a file.

    ln -s test symlink

    Creates a symbolic link named symlink that points to the file test Typing "ls -i test symlink" will show the

    two files are different with different inodes. Typing "ls -l test symlink" will show that symlink points tothe file test.

    locate- A fast database driven file locator.

    slocate -u

    This command builds the slocate database. It will take several minutes to complete this command.Thiscommand must be used before searching for files, however cron runs this command periodically onmost systems.locate whereis Lists all files whose names contain the string "whereis". directory.

  • 8/6/2019 linux_RV

    4/46

    more - Allows file contents or piped output to be sent to the screen one page at a time

    less - Opposite of the more command

    cat- Sends file contents to standard output. This is a way to list the contents of short files to thescreen. It works well with piping.

    whereis - Report all known instances of a command

    wc - Print byte, word, and line countsbg

    bg jobs Places the current job (or, by using the alternative form, the specified jobs) in the background,suspending its execution so that a new user prompt appears immediately. Use the jobs command todiscover the identities of background jobs.

    cal month year- Prints a calendar for the specified month of the specified year.

    cat files- Prints the contents of the specified files.

    clear - Clears the terminal screen.

    cmp file1 file2 - Compares two files, reporting all discrepancies. Similar to the diff command, though

    the output format differs.

    diff file1 file2- Compares two files, reporting all discrepancies. Similar to the cmp command, thoughthe output format differs.

    dmesg - Prints the messages resulting from the most recent system boot.

    fg

    fg jobs - Brings the current job (or the specified jobs) to the foreground.

    file files - Determines and prints a description of the type of each specified file.

    find path -name pattern -print

    Searches the specified path for files with names matching the specified pattern (usually enclosed in

    single quotes) and prints their names. The find command has many other arguments and functions; seethe online documentation.

    finger users - Prints descriptions of the specified users.

    free - Displays the amount of used and free system memory.

    ftp hostname

    Opens an FTP connection to the specified host, allowing files to be transferred. The FTP programprovides subcommands for accomplishing file transfers; see the online documentation.

    head files - Prints the first several lines of each specified file.

    ispell files - Checks the spelling of the contents of the specified files.

    kill process_ids

    kill - signal process_ids

    kill -l

    Kills the specified processes, sends the specified processes the specified signal (given as a number orname), or prints a list of available signals.

    killall program

    killall - signal program

  • 8/6/2019 linux_RV

    5/46

    Kills all processes that are instances of the specified program or sends the specified signal to allprocesses that are instances of the specified program.

    mail - Launches a simple mail client that permits sending and receiving email messages.

    man title

    man section title - Prints the specified man page.

    ping host- Sends an echo request via TCP/IP to the specified host. A response confirms that the host isoperational.

    reboot- Reboots the system (requires root privileges).

    shutdown minutes

    shutdown -r minutes

    Shuts down the system after the specified number of minutes elapses (requires root privileges). The -roption causes the system to be rebooted once it has shut down.

    sleep time - Causes the command interpreter to pause for the specified number of seconds.

    sort files - Sorts the specified files. The command has many useful arguments; see the online

    documentation.

    split file - Splits a file into several smaller files. The command has many arguments; see the onlinedocumentation

    sync - Completes all pending input/output operations (requires root privileges).

    telnet host- Opens a login session on the specified host.

    top - Prints a display of system processes that's continually updated until the user presses the q key.

    traceroute host- Uses echo requests to determine and print a network path to the host.

    uptime - Prints the system uptime.

    w - Prints the current system users.

    wall - Prints a message to each user except those who've disabled message reception. Type Ctrl-D toend the message.

    Linux file attributes

    Linux files are setup so access to them is controlled. There are three types of access:

    1. read ,2. write and 3. execute

    Each file belongs to a specific user and group. Access to the files is controlled by user, group, and what iscalled other. The term, other, is used to refer to someone who is not the user (owner) of the file, nor is the

    person a member of the group the file belongs to.

    File names and permission characters

    File names can be up to 256 characters long with "-", "_", and "." characters along with letters andnumbers.When a long file listing is done, there are 10 characters that are shown on the left that indicate type andpermissions of the file. File permissions are shown according to the following syntax example:

  • 8/6/2019 linux_RV

    6/46

    drwerwerwe

    There are a total of 10 characters in this example, as in all Linux files. The first character indicates thetype of file, and the next three indicate read, write, and execute permission for each of the three usertypes, user, group and other. Since there are three types of permission for three users, there are a total ofnine permission bits. The table below shows the syntax:

    1 2 3 4 5 6 7 8 9 10

    File User Permissions Group Permissions Other Permissions

    Type Read Write Execute Read Write Execute Read Write Execute

    d r w e r w e r w e

    Character 1 is the type of file: - is ordinary, d is directory, l is link. Characters 2-4 show owner permissions. Character 2 indicates read permission, character 3 indicates

    write permission, and character 4 indicates execute permission. Characters 5-7 show group permissions. Character 5=read, 6=write, 7=execute Characters 8-10 show permissions for all other users. Character 8=read, 9=write, 10=execute

    There are 5 possible characters in the permission fields. They are:

    r = read - This is only found in the read field. w = write - This is only found in the write field. x = execute - This is only found in the execute field. s = setuid - This is only found in the execute field. If there is a "-" in a particular location, there is no permission. This may be found in any field whether

    read, write, or execute field.

    Examples

    Type "ls -l" and a listing like the following is displayed:

    total 10

    drwxrwxrwx 4 george team1 122 Dec 12 18:02 Projects

    -rw-rw-rw- 1 george team1 1873 Aug 23 08:34 test

    -rw-rw-rw- 1 george team1 1234 Sep 12 11:13 datafile

    Which means the following:

    Type and # of Files's File's Size in Date of last Filename

    Permission field Links Owner Group Bytes modification

    | | | | | | |drwxrwxrwx 4 george team1 122 Dec 12 18:02 Projects

    The fields are as follows:

    1. Type field: The first character in the field indicates a file type of one of the following:o d = directory

    o l = symbolic link

    o s = socket

  • 8/6/2019 linux_RV

    7/46

    o p = named pipe

    o - = regular file

    o c= character (unbuffered) device file special

    o b=block (buffered) device file special

    2. Links: The number of directory entries that refer to the file. In our example, there are four.

    3. The file's owner in our example is George.4. The group the file belongs to. In our example, the group is team1.5. The size of the file in bytes6. The last modification date. If the file is recent, the date and time is shown. If the file is not in the

    current year, the year is shown rather than time.7. The name of the file.

    Set User Identification Attribute

    The file permissions bits include an execute permission bit for file owner, group and other. When the executebit for the owner is set to "s" the set user ID bit is set. When the execute bit for the group is set to "s", the setgroup ID bit is set and the user running the program is given access based on access permission for the groupthe file belongs to. The following command:

    chmod +s myfile

    sets the user ID bit on the file "myfile". The command:

    chmod g+s myfile

    sets the group ID bit on the file "myfile".

    The listing below shows a listing of two files that have the group or user ID bit set.

    -rws--x--x 1 root root 14024 Sep 9 1999 chfn-rwxr-sr-x 1 root mail 12072 Aug 16 1999 lockfile

    The files chfn and lockfile are located in the directory "/usr/bin". The "s" takes the place of the normallocation of the execute bit in the file listings above.

    Directory Permissions

    There are two special bits in the permissions field of directories. They are:

    s - Set group ID t - Save text attribute (sticky bit) - The user may delete or modify only those files in the directory that

    they own or have write permission for.

    Save text attribute

    The /tmp directory is typically world-writable and looks like this in a listing:

  • 8/6/2019 linux_RV

    8/46

    drwxrwxrwt 13 root root 4096 Apr 15 08:05 tmp

    Everyone can read, write, and access the directory. The "t'' indicates that only the user (and root, of course)that created a file in this directory can delete that file.

    To set the sticky bit in a directory, do the following:

    chmod +t data

    This option should be used carefully. A possible alternative to this is

    1. Create a directory in the user's home directory to which he or she can write temporary files.2. Set the TMPDIR environment variable using each user's login script.3. Programs using the tempnam(3) function will look for the TMPDIR variable and use it, instead of

    writing to the /tmp directory.

    Directory Set Group ID

    This attribute is helpful when several users need access to certain files. If the users work in a directory withthe setgid attribute set then any files created in the directory by any of the users will have the permission ofthe group. For example, the administrator can create a group called spcprj and add the users Kathy and Markto the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Markalthough in different primary groups can work in the directory and have full access to all files in thatdirectory, but still not be able to access files in each other's primary group.

    The following command will set the GID bit on a directory:

    chmod g+s spcprjdir

    The directory listing of the directory "spcprjdir":

    drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir

    The "s'' in place of the execute bit in the group permissions causes all files written to the directory "spcprjdir"to belong to the group "spcprj" .

    Examples

    Below are examples of making changes to permissions:

    chmod u+x myfile Gives the user execute permission on myfile.

    chmod +x myfile Gives everyone execute permission on myfile.chmod 400 myfile Gives the user read permission, and removes all other permission. These permissions are

    specified in octal, the first char is for the user, second for the group and the third is forother. The high bit (4) is for read access, the middle bit (2) os for write access, and thelow bit (1) is for execute access.

    chmod 764 myfile Gives user full access, group read and write access, and other read access.

    chmod 751 myfile Gives user full access, group read and execute permission, and other, execute permission

  • 8/6/2019 linux_RV

    9/46

    chmod go=rx myfile Remove read and execute permissions for the group and other.

    Umask Settings

    The umask command is used to set and determine the default file creation permissions on the system. It is theoctal complement of the desired file mode for the specific file type. Default permissions are:

    777 - Executable files 666 - Text files

    These defaults are set allowing all users to execute an executable file and not to execute a text file. Thedefaults allow all users can read and write the file.

    The permission for the creation of new executable files is calculated by subtracting the umask value from thedefault permission value for the file type being created. An example for a text file is shown below with aumask value of 022:

    666 Default Permission for text file-022 Minus the umask value-----644 Allowed Permissions

    Therefore the umask value is an expression of the permissions the user, group and world will not have as adefault with regard to reading, writing, or executing the file. The umask value here means the group the filebelongs to and users other than the owner will not be able to write to the file. In this case, when a new text fileis created it will have a file permission value of 644, which means the owner can read and write the file, butmembers of the group the file belongs to, and all others can only read the file.

    Wild cards (Filename Shorthand or meta Characters)

    Wild card/Shorthand

    Meaning Examples

    *Matches any string orgroup of characters.

    $ ls * will show all files

    $ ls a*will show all files whose first name is startingwith letter 'a'

    $ ls *.c will show all files having extension .c

    $ ls ut*.cwill show all files having extension .c but filename must begin with 'ut'.

    ? Matches any singlecharacter.

    $ ls ?will show all files whose names are 1 characterlong

    $ ls fo?will show all files whose names are 3 characterlong and file name begin with fo

    [...]Matches any one of theenclosed characters

    $ ls [abc]* will show all files beginning with letters a,b,c

    Note:

    [..-..] A pair of characters separated by a minus sign denotes a range.

  • 8/6/2019 linux_RV

    10/46

    Example:$ ls /bin/[a-c]*

    Will show all files name beginning with letter a,b or c like

    /bin/arch /bin/awk /bin/bsh /bin/chmod /bin/cp/bin/ash /bin/basename /bin/cat /bin/chown /bin/cpio/bin/ash.static /bin/bash /bin/chgrp /bin/consolechars /bin/csh

    But$ ls /bin/[!a-o]

    $ ls /bin/[^a-o]

    If the first character following the [ is a ! or a ^ ,then any character not enclosed is matched i.e. do not show usfile name that beginning with a,b,c,e...o, like

    /bin/ps /bin/rvi /bin/sleep /bin/touch /bin/view/bin/pwd /bin/rview /bin/sort /bin/true /bin/wcomp

    Pipes

    A pipe is a way to connect the output of one program to the input of another program without any temporaryfile.

    Pipe Defined as:"A pipe is nothing but a temporary storage place where the output of one command is stored and then passedas the input for second command. Pipes are used to run more than two commands ( Multiple commands) from

    same command line."

    Syntax:

    command1 | command2

    Examles:

    Command using Pipes Meaning or Use of Pipes

  • 8/6/2019 linux_RV

    11/46

    $ ls | moreOutput of ls command is given as input to more command So that output isprinted one screen full page at a time.

    $ who | sortOutput of who command is given as input to sort command So that it will printsorted list of users

    $ who | sort > user_list Same as above except output of sort is send to (redirected) user_list file

    $ who | wc -lOutput of who command is given as input to wc command So that it will numberof user who logon to system

    $ ls -l | wc -lOutput of ls command is given as input to wc command So that it will printnumber of files in current directory.

    $ who | grep raju

    Output of who command is given as input to grep command So that it will print ifparticular user name if he is logon or nothing is printed (To see particular user islogon or not)

    Linux Command Related with Process

    Following tables most commonly used command(s) with process:

    For this purpose Use this Command Examples*

    To see currently running process ps $ ps

    To stop any process by PID i.e. to kill process kill {PID} $ kill 1012

    To stop processes by name i.e. to kill process killall {Process-name} $ killall httpd

    To get information about all running process ps -ag $ ps -ag

    To stop all process except your shell kill 0 $ kill 0

    For background processing (With &, use to put particular

    command and program in background)

    linux-command & $ ls / -R | wc -l &

    To display the owner of the processes along with theprocesses

    ps aux $ ps aux

    To see if a particular process is running or not. For thispurpose you have to use ps command in combination withthe grep command

    ps ax | grep process-U-want-to see

    For e.g. you want tosee whether Apacheweb server process isrunning or not thengive command$ ps ax | grep httpd

    To see currently running processes and other informationlike memory and CPU usage with real time updates.

    top $ top

    Note that to exit from topcommand press q.

    To display a tree of processes pstree $ pstree

    * To run some of this command you need to be root or equivalnt user.

    Answer to Process Section.

  • 8/6/2019 linux_RV

    12/46

    2) How you will you find out the both running process (MP3 Playing & Letter typing)?Ans.: Try $ ps aux or$ ps ax | grep process-you-want-to-search

    3) "Currently only two Process are running in your Linux/PC environment", Is it True or False?, And how youwill verify this?

    Ans.: No its not true, when you start Linux Os, various process start in background for different purpose. Toverify this simply use top orps aux command.

    4) You don't want to listen music (MP3 Files) but want to continue with other work on PC, you will take anyof the following action:

    1. Turn off Speakers2. Turn off Computer / Shutdown Linux Os3. Kill the MP3 playing process4. None of the above

    Ans.: Use action no. 3 i.e. kill the MP3 process.Tip: First find the PID of MP3 playing process by issuing command:$ ps ax | grep mp3-process-name

    Then in the first column you will get PID of process. Kill this PID to end the process as:$ kill PID

    Or you can try killall command to kill process by name as follows:$ killall mp3-process-name

    Linux Console (Screen)

    As you know in Linux everything is considered as a file, our console is one of such special file. You can writespecial character sequences to console, which control every aspects of the console like Colors on screen, Boldor Blinking text effects, clearing the screen, showing text boxes etc. For this purpose we have to use specialcode called escape sequence code.

    By default what ever you send to console it is printed as its. For e.g. consider following echo statement,$ echo "Hello World"

    Hello WorldAbove echo statement prints sequence of character on screen., but if there is any special escape sequence(control character) in sequence , then first some action is taken according to escape sequence (or controlcharacter) and then normal character is printed on console. For e.g. following echo command prints message

    in Blue color on console$ echo -e "\033[34m Hello Colorful World!"

    Hello Colorful World!

    Above echo statement uses ANSI escape sequence (\033[34m), above entire string ( i.e. "\033[34m HelloColorful World!" ) is process as follows

  • 8/6/2019 linux_RV

    13/46

    1) First \033, is escape character, which causes to take some action2) Here it set screen foreground color to Blue using [34m escape code.3) Then it prints our normal message Hello Colorful World! in blue color.

    You can use echo statement to print message, to use ANSI escape sequence you must use -e option (switch)

    with echo statement, general syntax is as followsSyntaxecho -e "\033[escape-code your-message"

    In above syntax you have to use\033[ as its with different escape-code for different operations. As soon asconsole receives the message it start to process/read it, and if it found escape character (\033) it moves toescape mode, then it read "[" character and moves into Command Sequence Introduction (CSI) mode. InCSI mode console reads a series of ASCII-coded decimal numbers (know as parameter) which are separatedby semicolon (;) . This numbers are read until console action letter or character is not found (whichdetermines what action to take). In above example

    \033 Escape character[ Start of CSI

    34 34 is parameter

    m m is letter (specifies action)

    Following table show important list of such escape-code/action letter or character

    Character or letter Use in CSI Examples

    h Set the ANSI mode echo -e "\033[h"

    l Clears the ANSI mode echo -e "\033[l"

    m

    Useful to show characters in differentcolors or effects such as BOLD andBlink, see below for parameter takenby m.

    echo -e "\033[35m Hello World"

    qTurns keyboard num lock, caps lock,scroll lock LED on or off, see below.

    echo -e "\033[2q"

    sStores the current cursor x,y position(col , row position) and attributes

    echo -e "\033[7s"

    u Restores cursor position and attributes echo -e "\033[8u"

    m understand following parameters

    Parameter Meaning Example

    0

    Sets default color scheme (Whiteforeground and Blackbackground), normal intensity, noblinking etc.

    1 Set BOLD intensity $ echo -e "I am \033[1m BOLD \033[0m Person"

  • 8/6/2019 linux_RV

    14/46

    I am BOLD PersonPrints BOLD word in bold intensity and next ANSISequence remove bold effect (\033[0m)

    2 Set dim intensity $ echo -e "\033[1m BOLD \033[2m DIM \033[0m"

    5 Blink Effect $ echo -e "\033[5m Flash! \033[0m"

    7Reverse video effect i.e. Blackforeground and white backgroundin default color scheme

    $ echo -e "\033[7m Linux OS! Best OS!! \033[0m"

    11

    Shows special control character asgraphics character. For e.g. Beforeissuing this command press alt key(hold down it) from numeric keypad press 178 and leave both key;nothing will be printed. Now give--> command shown in example

    and try the above, it works. (Heyyou must know extended ASCIICharacter for this!!!)

    $ press alt + 178

    $ echo -e "\033[11m"

    $ press alt + 178

    $ echo -e "\033[0m"

    $ press alt + 178

    25 Removes/disables blink effect

    27 Removes/disables reverse effect

    30 - 37

    Set foreground color31 - RED32 - Greenxx - Try to find yourself this left asexercise for you :-)

    $ echo -e "\033[31m I am in Red"

    40 - 47Set background colorxx - Try to find yourself this left asexercise for you :-)

    $ echo -e "\033[44m Wow!!!"

    q understand following parameters

    Parameters Meaning

    0 Turns off all LEDs on Keyboard

    1 Scroll lock LED on and others off

    2 Num lock LED on and others off

    3 Caps lock LED on and others off Shell Built in Variables

    Shell Built in Variables Meaning

    $#Number of command line arguments. Useful to test no. of command lineargs in shell script.

  • 8/6/2019 linux_RV

    15/46

    $* All arguments to shell

    $@ Same as above

    $- Option supplied to shell

    $$ PID of shell

    $! PID of last started background process (started with &)

    Shell programming

    if condition

    if condition which is used for decision making in shell script, If given condition is true then command1 isexecuted.Syntax:

    if condition

    thencommand1 if condition is true or if exit status

    of condition is 0 (zero)

    ...

    ...

    fi

    Condition is defined as:"Condition is nothing but comparison between two values."

    For compression you can use test or [ expr ] statements or even exist status can be also used.

    Expreession is defined as:

    "An expression is nothing but combination of values, relational operator (such as >,

  • 8/6/2019 linux_RV

    16/46

    if cat $1thenecho -e "\n\nFile $1, found and successfully echoed"fi

    Run above script as:

    $ chmod 755 showfile$./showfile foo

    Shell script name is showfile ($0) and foo is argument (which is $1).Then shell compare it as follows:if cat $1 which is expanded to if cat foo.

    Detailed explanation

    if cat command finds foo file and if its successfully shown on screen, it means our cat command is successfuland its exist status is 0 (indicates success), So our if condition is also true and hence statement echo -e"\n\nFile $1, found and successfully echoed" is proceed by shell. Now if cat command is not successful then itreturns non-zero value (indicates some sort of failure) and this statement echo -e "\n\nFile $1, found andsuccessfully echoed" is skipped by our shell.

    Exercise

    Write shell script as follows:

    cat > trmif## Script to test rm command and exist status#if rm $1thenecho "$1 file deleted"fi

    Press Ctrl + d to save$ chmod 755 trmif

    Answer the following question in referance to above script:(A) foo file exists on your disk and you give command, $ ./trmfi foo what will be output?(B) If bar file not present on your disk and you give command, $ ./trmfi bar what will be output?(C) And if you type $ ./trmfi What will be output?

    test command or [ expr ]

    test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0), otherwise

    returns nonzero for false.Syntax:test expression OR [ expression ]

    Example:

    Following script determine whether given argument number is positive.

    $ cat > ispostive

  • 8/6/2019 linux_RV

    17/46

    #!/bin/sh## Script to see whether argument is positive#if test $1 -gt 0thenecho "$1 number is positive"fi

    Run it as follows$ chmod 755 ispostive

    $ ispostive 5

    5 number is positive

    $ispostive -45

    Nothing is printed

    $ispostive

    ./ispostive: test: -gt: unary operator expected

    Detailed explanation

    The line, if test $1 -gt 0 , test to see if first command line argument($1) is greater than 0. If it is true(0) thentest will return 0 and output will printed as 5 number is positive but for -45 argument there is no outputbecause our condition is not true(0) (no -45 is not greater than 0) hence echo statement is skipped. And for laststatement we have not supplied any argument hence error ./ispostive: test: -gt: unary operator expected, isgenerated by shell , to avoid such error we can test whether command line argument is supplied or not.

    test or [ expr ] works with1.Integer ( Number without decimal point)

    2.File types3.Character strings

    For Mathematics, use following operator in Shell Script

    Mathematical

    Operator in Shell

    Script

    MeaningNormal Arithmetical/

    Mathematical StatementsBut in Shell

    For test statement

    with if command

    For [ expr ]

    statement with if

    command-eq is equal to 5 == 6 if test 5 -eq 6 if [ 5 -eq 6 ]

    -ne is not equal to 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ]

    -lt is less than 5 < 6 if test 5 -lt 6 if [ 5 -lt 6 ]

    -leis less than orequal to

    5

  • 8/6/2019 linux_RV

    18/46

    -gt is greater than 5 > 6 if test 5 -gt 6 if [ 5 -gt 6 ]

    -geis greater thanor equal to

    5 >= 6 if test 5 -ge 6 if [ 5 -ge 6 ]

    NOTE: == is equal, != is not equal.

    For string Comparisons use

    Operator Meaning

    string1 = string2 string1 is equal to string2

    string1 != string2 string1 is NOT equal to string2

    string1 string1 is NOT NULL or not defined

    -n string1 string1 is NOT NULL and does exist

    -z string1 string1 is NULL and does exist

    Shell also test for file and directory types

    Test Meaning

    -s file Non empty file

    -f file Is File exist or normal file and not a directory

    -d dir Is Directory exist and not a file

    -w file Is writeable file

    -r file Is read-only file

    -x file Is file is executable

    Logical Operators

    Logical operators are used to combine two or more condition at a time

    Operator Meaning

    ! expression Logical NOT

    expression1 -a expression2 Logical AND

    expression1 -o expression2 Logical OR

    if...else...fi

    If given condition is true then command1 is executed otherwise command2 is executed.Syntax:

    if conditionthen

    condition is zero (true - 0)execute all commands up to else statement

    else

  • 8/6/2019 linux_RV

    19/46

    if condition is not true thenexecute all commands up to fi

    fi

    For e.g. Write Script as follows:

    $ vi isnump_n

    #!/bin/sh## Script to see whether argument is positive or negative#if [ $# -eq 0 ]thenecho "$0 : You must give/supply one integers"exit 1fi

    if test $1 -gt 0thenecho "$1 number is positive"

    elseecho "$1 number is negative"fi

    Try it as follows:$ chmod 755 isnump_n

    $ isnump_n 5

    5 number is positive

    $ isnump_n -45

    -45 number is negative

    $ isnump_n

    ./ispos_n : You must give/supply one integers

    $ isnump_n 0

    0 number is negative

    Detailed explanation

    First script checks whether command line argument is given or not, if not given then it print error message as"./ispos_n : You must give/supply one integers". if statement checks whether number of argument ($#) passedto script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false and if nocommand line argument is given then this if statement is true. The echo command i.e.echo "$0 : You must give/supply one integers"

    | || |1 2

    1 will print Name of script2 will print this error messageAnd finally statement exit 1 causes normal program termination with exit status 1 (nonzero means script is notsuccessfully run).

  • 8/6/2019 linux_RV

    20/46

    The last sample run $ isnump_n 0 , gives output as "0 number is negative", because given argument is not >0, hence condition is false and it's taken as negative number. To avoid this replace second if statement with iftest $1 -ge 0.

    Nested if-else-fi

    You can write the entire if-else construct within either the body of the if statement of the body of an elsestatement. This is called the nesting of ifs.

    $ vi nestedif.shosch=0

    echo "1. Unix (Sun Os)"echo "2. Linux (Red Hat)"echo -n "Select your os choice [1 or 2]? "read osch

    if [ $osch -eq 1 ] ; then

    echo "You Pick up Unix (Sun Os)"

    else #### nested if i.e. if within if ######

    if [ $osch -eq 2 ] ; thenecho "You Pick up Linux (Red Hat)"

    elseecho "What you don't like Unix/Linux OS."

    fifi

    Run the above shell script as follows:

    $ chmod +x nestedif.sh$ ./nestedif.sh

    1. Unix (Sun Os)

    2. Linux (Red Hat)

    Select you os choice [1 or 2]? 1

    You Pick up Unix (Sun Os)

    $ ./nestedif.sh

    1. Unix (Sun Os)

    2. Linux (Red Hat)Select you os choice [1 or 2]? 2

    You Pick up Linux (Red Hat)

    $ ./nestedif.sh

    1. Unix (Sun Os)2. Linux (Red Hat)

    Select you os choice [1 or 2]? 3

    What you don't like Unix/Linux OS.

  • 8/6/2019 linux_RV

    21/46

    Note that Second if-else constuct is nested in the first else statement. If the condition in the first ifstatement isfalse the the condition in the second ifstatement is checked. If it is false as well the final else statement isexecuted.

    You can use the nested ifs as follows also:

    Syntax:

    if conditionthen

    if conditionthen

    .....

    ..do this

    else......do this

    fielse

    ...

    .....do this

    fi

    Multilevel if-then-else

    Syntax:if conditionthen

    condition is zero (true - 0)execute all commands up to elif statement

    elif condition1then

    condition1 is zero (true - 0)execute all commands up to elif statement

    elif condition2then

    condition2 is zero (true - 0)execute all commands up to elif statement

    elseNone of the above condtion,condtion1,condtion2 are true (i.e.all of the above nonzero or false)execute all commands up to fi

    fi

    For multilevel if-then-else statement try the following script:

  • 8/6/2019 linux_RV

    22/46

    $ cat > elf##!/bin/sh# Script to test if..elif...else#if [ $1 -gt 0 ]; thenecho "$1 is positive"

    elif [ $1 -lt 0 ]thenecho "$1 is negative"

    elif [ $1 -eq 0 ]thenecho "$1 is zero"

    elseecho "Opps! $1 is not number, give number"

    fi

    Try above script as follows:$ chmod 755 elf

    $ ./elf 1

    $ ./elf -2$ ./elf 0

    $ ./elf a

    Here o/p for last sample run:./elf: [: -gt: unary operator expected./elf: [: -lt: unary operator expected./elf: [: -eq: unary operator expectedOpps! a is not number, give numberAbove program gives error for last run, here integer comparison is expected therefore error like "./elf: [: -gt:unary operator expected" occurs, but still our program notify this error to user by providing message "Opps!a is not number, give number".

    Loops in Shell Scripts

    Loop defined as:"Computer can repeat particular instruction again and again, until particular condition satisfies. A group ofinstruction that is executed repeatedly is called a loop."

    Bash supports:

    for loop while loop

    Note that in each and every loop,

    (a) First, the variable used in loop condition must be initialized, then execution of the loop begins.

    (b) A test (condition) is made at the beginning of each iteration.

    (c) The body of loop ends with a statement that modifies the value of the test (condition) variable.

  • 8/6/2019 linux_RV

    23/46

    for Loop

    Syntax:for { variable name } in { list }

    do

    execute one for each item in the list until the list is

    not finished (And repeat all statement between do and done)

    done

    Before try to understand above syntax try the following script:

    $ cat > testforfor i in 1 2 3 4 5doecho "Welcome $i times"done

    Run it above script as follows:$ chmod +x testfor

    $ ./testfor

    The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5, The shellexecute echo statement for each assignment of i. (This is usually know as iteration) This process will continueuntil all the items in the list were not finished, because of this it will repeat 5 echo statements. To make youidea more clear try following script:

    $ cat > mtable#!/bin/sh##Script to test for loop##if [ $# -eq 0 ]

    thenecho "Error - Number missing form command line argument"echo "Syntax : $0 number"echo "Use to print multiplication table for given number"exit 1fin=$1for i in 1 2 3 4 5 6 7 8 9 10doecho "$n * $i = `expr $i \* $n`"done

    Save above script and run it as:$ chmod 755 mtable

    $ ./mtable 7$ ./mtable

    For first run, above script print multiplication table of given number where i = 1,2 ... 10 is multiply by given n(here command line argument 7) in order to produce multiplication table as7 * 1 = 77 * 2 = 14.....

  • 8/6/2019 linux_RV

    24/46

    7 * 10 = 70And for second test run, it will print message -Error - Number missing form command line argument

    Syntax : ./mtable number

    Use to print multiplication table for given number

    This happened because we have not supplied given number for which we want multiplication table, Hencescript is showing Error message, Syntax and usage of our script. This is good idea if our program takes someargument, let the user know what is use of the script and how to used the script.Note that to terminate our script we used 'exit 1' command which takes 1 as argument (1 indicates error andtherefore script is terminated)

    Even you can use following syntax:

    Syntax:

    for (( expr1; expr2; expr3 ))do

    ........

    repeat all statements between do anddone until expr2 is TRUE

    Done

    In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to initialize variables forthe loop.All the statements between do and done is executed repeatedly UNTIL the value ofexpr2 is TRUE.AFTER each iteration of the loop, expr3 is evaluated. This is usually use to increment a loop counter.

    $ cat > for2for (( i = 0 ; i

  • 8/6/2019 linux_RV

    25/46

    $ vi nestedfor.shfor (( i = 1; i

  • 8/6/2019 linux_RV

    26/46

    Above shell script cab be explained as follows:

    Command(s)/Statements Explanation

    for (( i = 1; i

  • 8/6/2019 linux_RV

    27/46

    increasingly in interactive development environments such as Microsoft's VisualC++. Regular expressions are made up of normal characters andmetacharacters. Normal characters include upper and lower case letters anddigits. The metacharacters have special meanings and are described in detailbelow.

    In the simplest case, a regular expression looks like a standard search string.For example, the regular expression "testing" contains no metacharacters. It willmatch "testing" and "123testing" but it will not match "Testing".

    The table below lists metacharacters and a short explanation of theirmeaning.

    Metacharacter

    Description

    . Matches any single character. For example theregular expression r.t would match the strings rat,rut, r t, but not root.

    $ Matches the end of a line. For example, the regularexpression weasel$ would match the end of the string"He's a weasel" but not the string "They are a bunchof weasels."

    ^ Matches the beginning of a line. For example, the

    regular expression ^When in would match thebeginning of the string "When in the course of humanevents" but would not match "What and When in the".

    * Matches zero or more occurences of the characterimmediately preceding. For example, the regularexpression .* means match any number of anycharacters.

    \ This is the quoting character, use it to treat thefollowing character as an ordinary character. For

    example, \$ is used to match the dollar sign character($) rather than the end of a line. Similarly, theexpression \. is used to match the period characterrather than any single character.

    [ ]

    [c1-c2][^c1-c2]

    Matches any one of the characters between thebrackets. For example, the regular expression r[aou]tmatches rat, rot, and rut, but not ret. Ranges of

  • 8/6/2019 linux_RV

    28/46

    characters can specified by using a hyphen. Forexample, the regular expression [0-9] means matchany digit. Multiple ranges can be specified as well.

    The regular expression [A-Za-z] means match anyupper or lower case letter. To match any character

    exceptthose in the range, the complement range,use the caret as the first character after the openingbracket. For example, the expression [^269A-Z] willmatch any characters except 2, 6, 9, and upper caseletters.

    \< \> Matches the beginning (\) or a word. Forexample, \

  • 8/6/2019 linux_RV

    29/46

    The simplest metacharacter is the dot. It matches any one character(excluding the newline character). Consider a file named test.txt consisting ofthe following lines:

    he is a rat

    he is in a rutthe food is RottenI like root beer

    We can use grep to test our regular expressions. Grep uses the regularexpression we supply and tries to match it to every line of the file. It prints alllines where the regular expression matches at least one sequence of characterson a line. The commandgrep r.t test.txt

    searches for the regular expression r.t in each line of test.txt and prints thematching lines. The regular expression r.t matches an r followed by anycharacter followed by a t. It will match rat and rut. It does not match the Rot in

    Rotten because regular expressions are case sensitive. To match both the upperand lower the square brackets (character range metacharacters) can be used.The regular expression [Rr] matches either Ror r. So, to match an upper or lowercase r followed by any character followed by the character t the regularexpression [Rr].t will do the trick.

    Simple ExamplesHere are a few representative, simple examples.

    vi command What it does

    :%s/ */ /g Change 1 or more spaces into a single space.:%s/ *$// Remove all spaces from the end of the line.

    :%s/^/ / Insert a space at the beginning of every line.

    :%s/^[0-9][0-9]* // Remove all numbers at the beginning of a line.

    :%s/b[aeio]g/bug/g Change all occurences ofbag, beg, big, and bog, to bug.

    :%s/t\([aou]\)g/h\1t/gChange all occurences oftag, tog, and tug to hat, hot, andhug respectively.

    Medium Examples (Strange Incantations)Example 1

    Change all instances of foo(a,b,c) to foo(b,a,c). where a, b, and c can be anyparameters supplied to foo(). That is, we must be able to make changes like thefollowing:

  • 8/6/2019 linux_RV

    30/46

    Before Afterfoo(10,7,2) foo(7,10,2)

    foo(x+13,y-2,10) foo(y-2,x+13,10)

    foo( bar(8), x+y+z, 5) foo( x+y+z, bar(8), 5)

    The following substitution command will do the trick :

    :%s/foo(\([^,]*\),\([^,]*\),\([^)]*\))/foo(\2,\1,\3)/g

    Now, let's break this apart and analyze what's happening. The idea behind thisexpression is to identify invocations of foo() with three parameters between theparentheses. The first parameter is identified by the regular expression \([^,]*\),which we can analyze from the inside out.

    [^,] means any character which is not a comma[^,]* means 0 or more characters which are not commas

    \([^,]*\)tags the non-comma characters as \1 for use in the replacement part

    of the command

    \([^,]*\),means that we must match 0 or more non-comma characters whichare followed by a comma. The non-comma characters are tagged.

    Why would we use an expression like [^,]*, instead of something morestraightforward like .*, to match the first parameter? Consider applying thepattern .*, to the string "10,7,2". Should it match "10," or "10,7," ? To resolvethis ambiguity, regular expressions will always match the longest string possible.In this case "10,7," which covers two parameters instead of one parameter likewe want. So, by using the expression [^,]*, we force the pattern to match allcharacters up to the first comma.

    The expression up to this point is: foo(\([^,]*\), and can be roughly translatedas "after you find foo( tag all characters up to the next comma as \1". We tag thesecond parameter just like the first and it can be referenced as \2. The tag usedon the third parameter is exactly like the others except that we search for allcharacters up to the right parenthesis. This pattern guarantees that we updateonly those instances of foo() where 3 parameters are specified. In these times offunction and method overloading, being explicit often proves to be useful. In thesubstitution portion of the command, we explicitly enter the invocation of foo()as we want it, referencing the matched patterns in the new order where the first

    and second parameter have been switched.

    Example 2We have a CSV (comma separated value) file with information we need, but inthe wrong format. The columns of data are currently arranged in the followingorder: Name, Company Name, State, Postal Code. We need to reorganize thedata into the following order in order to use it with a particular piece of software:

  • 8/6/2019 linux_RV

    31/46

    Name, State-Postal Code, Company Name. This means that we must change theorder of the columns in addition to merging two columns to form a new columnvalue. The particular piece of software that needs this data will not work if thereare any whitespace characters (spaces or tabs) before or after the commas. Sowe must remove whitespace around the commas.

    Here are a few lines from the data we have:

    Bill Jones, HI-TEK Corporation , CA, 95011Sharon Lee Smith, Design Works Incorporated, CA, 95012B. Amos , Hill Street Cafe, CA, 95013Alexander Weatherworth, The Crafts Store, CA, 95014...

    We need to transform them to look like this:Bill Jones,CA 95011,HI-TEK CorporationSharon Lee Smith,CA 95012,Design Works IncorporatedB. Amos,CA 95013,Hill Street CafeAlexander Weatherworth,CA 95014,The Crafts Store...

    We'll look at two regular expressions to solve this problem. The first moves thecolumns around and merges the data. The second removes the excess spaces.

    Here is the first pass at a substitution command that will solve the problem:

    :%s/\([^,]*\),\([^,]*\),\([^,]*\),\(.*\)/\1,\3 \4,\2/

    The approach is similar to that of Example 1. The Name is matched by theexpression \([^,]*\), that is, all characters up to the first comma. The name canthen be referenced as \1 in the replacement pattern. The Company Name andState fields are matched just like the Name field and are referenced as \2 and \3in the replacement pattern. The last field is matched with the expression \(.*\)

    which can be translated as "match all characters through the end of the line".The replacement pattern is constructed by calling out each tagged expression inthe appropriate order and adding or not adding the delimeter.

    The following substitution command will remove the excess spaces:

    :%s/[ \t]*,[ \t]*/,/g

    To break it down: [ \t] matches a space or tab character; [ \t]* matches 0 ormore spaces or tabs; [ \t]*, matches 0 or more spaces or tabs followed by acomma; and finally [ \t]*,[ \t]* matches 0 or more spaces or tabs followed by acomma followed by 0 or more spaces or tabs. In the replacement pattern, we

    simply replace whatever we matched with a single comma. The optional gparameter is added to the end of the substitution command to apply thesubstitution to all commas in the line.

    Hard Examples (Magical Hieroglyphics)coming soon.

    Regular Expressions In Various Tools

  • 8/6/2019 linux_RV

    32/46

    You can use regular expressions in the Visual C++ editor. Select Edit->Replace, then be sure to check the checkbox labled "Regular expression". Forvi expressions of the form :%s/pat1/pat2/g set the Find What field topat1 and theReplace with field topat2. To simulate the range (% in this case) and the g optionyou will have to use the Replace All button or appropriate combinations of Find

    Next and Replace

    sedSed is a Stream EDitor which can be used to make changes to files or pipes.Here are a few interesting sed scripts. Assume that we're processing a file calledprice.txt.

    sed script Description

    sed 's/^$/d' price.txt removes all empty lines

    sed 's/^[ \t]*$/d' price.txt removes all lines containing onlywhitespacesed 's/"//g' price.txt remove all quotation marks

    awkAwk is a programming language which can be used to perform sophisticatedanalysis and manipulation of text data. For complete details, see the man pageawk(1). Its peculiar name is an acronym made up of the first character of itsauthors last names (Aho, Weinberger, and Kernighan).

    There are many good awk examples in the book The AWK ProgrammingLanguage (written by Aho, Weinberger, and Kernighan). Please don't form any

    broad opinions about awk's capabilities based on the following trivial samplescripts. For purposes of these examples, assume that we're working with a filecalled price.txt. As with sed, awk simply echos its output to its standard out.

    awk script Description

    awk '$0 !~ /^$/' price.txt removes all empty linesawk 'NF > 0' price.txt a better way to remove all lines in awk

    awk '$2 ~ /^[JT]/ {print $3}'

    price.txt

    print the third field of all lines whosesecond field begins with 'J' or 'T'

    awk '$2 !~ /[Mm]isc/ {print $3+ $4}' price.txt

    for all lines whose second field does notcontain 'Misc' or 'misc' print the sum ofcolumns 3 and 4 (assumed to be numbers).

    awk '$3 !~ /^[0-9]+\.[0-9]*$/{print $0}' price.txt

    print all lines where field 3 is not a number.The number must be of the form: d.d or d.where d is any number of digits from 0 to

    http://linuxreviews.org/man/sedhttp://linuxreviews.org/man/awk/http://linuxreviews.org/man/awk/http://linuxreviews.org/man/sedhttp://linuxreviews.org/man/awk/http://linuxreviews.org/man/awk/
  • 8/6/2019 linux_RV

    33/46

    9.

    awk '$2 ~ /John|Fred/ {print$0}' price.txt

    print the entire line if the second fieldcontains 'John' or 'Fred'

    Using grep commandThe grep command selects and prints lines from a file (or a bunch of files) that match a pattern. Let's say your friend Bill sent you anemail recently with his phone number, and you want to call him ASAP to order some books. Instead of launching your email programand sifting through all the messages, you can scan your in-box file, like this:

    grep 'number' /var/mail/hermiecan call No Starch Press at 800/420-7240. Office hours are

    noted that recently, an alarming number of alien spacecrafts

    among colleagues at a number of different organizationsHere, grep has pulled out just the lines that contain the word number. The first line is obviously what you were after, while the others

    just happened to match the pattern. The general form of the grep command is this:

    grep

    The most useful grep flags are shown here:

    -i Ignore uppercase and lowercase when comparing.-v Print only lines that do notmatch the pattern.-c Print only a count of the matching lines.-n Display the line number before each matching line.

    When grep performs its pattern matching, it expects you to provide a regular expression for the pattern. Regular expressions can bevery simple or quite complex, so we won't get into a lot of details here. Here are the most common types of regular expressions:

    abc Match lines containing the string "abc" anywhere.^abc Match lines starting with "abc."abc$ Match lines ending with "abc."a..c Match lines containing "a" and "c" separated by any two characters (the dot matches any single character).a.*c Match lines containing "a" and "c" separated by any number of characters (the dot- asterisk means match zero or morecharacters).

    Regular expressions also come into play when using vi, sed, awk, and other Unix commands. If you want to master Unix, take time tounderstand regular expressions. Here is a sample poem.txt file and some grep commands to demonstrate regular-expressionpattern matching:

    Mary had a little lamb

    Mary fried a lot of spam

    Jack ate a Spam sandwich

    Jill had a lamb spamwich

    To print all lines containing spam (respecting uppercase and lowercase), enter

    grep 'spam' poem.txt

    Mary fried a lot of spamJill had a lamb spamwich

    To print all lines containing spam (ignoring uppercase and lowercase), enter

    grep -i 'spam' poem.txt

    Mary fried a lot of spam

    Jack ate a Spam sandwich

    Jill had a lamb spamwich

  • 8/6/2019 linux_RV

    34/46

    To print just the number of lines containing the word spam (ignoring uppercase and lowercase), enter

    grep -ic 'spam' poem.txt

    3

    To print all lines notcontaining spam (ignoring uppercase and lowercase), enter

    grep -i -v 'spam' poem.txt

    Mary had a little lamb

    To print all lines starting with Mary, enter

    grep '^Mary' poem.txt

    Mary had a little lamb

    Mary fried a lot of spam

    To print all lines ending with ich, enter

    grep 'ich$' poem.txt

    Jack ate a Spam sandwichJill had a lamb spamwich

    To print all lines containing hadfollowed by lamb, enter

    grep 'had.*lamb' poem.txt

    Mary had a little lamb

    Jill had a lamb spamwich

    Here are some examples using grep:

    grep smug files {searchfiles for lines with 'smug'}

    grep '^smug' files {'smug' at the start of a line}

    grep 'smug$' files {'smug' at the end of a line}

    grep '^smug$' files {lines containing only 'smug'}

    grep '\^s' files {lines starting with '^s', "\" escapes the ^}

    grep '[Ss]mug' files {search for 'Smug' or 'smug'}

    grep 'B[oO][bB]' files {search for BOB, Bob, BOb or BoB }

    grep '^$' files {search for blank lines}

    grep '[0-9][0-9]' file {search for pairs of numeric digits}

    The vi editor uses \< \> to match characters at the beginning and/or end of a word boundary. A wordboundary is either the edge of the line or any character except a letter, digit or underscore "_". To look forif,

    but skip stiff, the expression is \. For the same logic in grep, invoke it with the -w option. And

    remember that regular expressions are case-sensitive. If you don't care about the case, the expression to match"if" would be [Ii][Ff], where the characters in square brackets define a character set from which the

    pattern must match one character. Alternatively, you could also invoke grep with the -i option to ignore case.

    Here are a few more examples ofgrep to show you what can be done:

  • 8/6/2019 linux_RV

    35/46

    grep '^From: ' /usr/mail/$USER {list your mail}

    grep '[a-zA-Z]' {any line with at least one letter}

    grep '[^a-zA-Z0-9] {anything not a letter or number}

    grep '[0-9]\{3\}-[0-9]\{4\}' {999-9999, like phone numbers}

    grep '^.$' {lines with exactly one character}

    grep '"smug"' {'smug' within double quotes}

    grep '"*smug"*' {'smug', with or without quotes}

    grep '^\.' {any line that starts with a Period "."}

    grep '^\.[a-z][a-z]' {line start with "." and 2 lc letters}

    Usepasswd to

    change your currentpassword

    Typepasswd and press enter. You'll see the message Changing passwordfor

    yourname.At the Old password: prompt, type in your old password .Then, at the Enter new password: prompt, type in your new password .The system double checks your new password. Beside the Verify: prompt, type the newpassword and press again.

    Create a secure password that combines parts of words and numbers. For instance, yourdog's name may be Rufus. He may have been born in 1980. Create a password that useparts of both the name and date of birth, such as 80rufuS. Note the use of at least onecapital letter. This is a fairly secure password and easy to remember.

    Usepwd to list the

    name of your currentdirectory

    Typepwd and hit enter. You'll see the full name of the directory you are currently in.

    This is your directory path and is very handy. This is especially handy when you forgetwhich directory youve changed to and are trying to run other commands.

    Working With file

    Manipulating FilesIncluded in this section are the commands needed to copy, delete, move, and rename files. Securityand permissions are also reviewed below in the chmod command.

    NOTE:All of these commandsshouldwork from your command prompt (regardless which shell you're using). And

    of course, if they don't work or help you, I apologize.

    Manipulating Files

    Command Summary Use

    chmod The chmod command allows you to alter access rights to files anddirectories. All files and directories have security permissions

  • 8/6/2019 linux_RV

    36/46

    that grant the user particular groups or all other users

    access.

    To view your files' settings, at the shell prompt type: ls -alt

    You should see some files with the following in front of them

    (an example follows):total 4

    drwxrwsr-x 7 reallyli reallyli 1024 Apr 6 14:30 .

    drwxr-s--x 22 reallyli reallyli 1024 Mar 30 18:20 ..

    d-wx-wx-wx 3 reallyli reallyli 1024 Apr 6 14:30 content

    drwxr-xr-x 2 reallyli reallyli 1024 Mar 25 20:43 files

    What do the letters mean in front of the files/directories mean?

    r indicates that it is readable (someone can view the filescontents)

    w indicates that it is writable (someone can edit the filescontents)

    x indicates that it is executable (someone can run the file, ifexecutable)

    - indicates that no permission to manipulate has been assigned

    When listing your files, the first character lets you know

    whether youre looking at a file or a directory. Its not part

    of the security settings. The next three characters indicate

    Your access restrictions. The next three indicate your group's

    permissions, and finally other users' permissions.

    Use chmod followed by the permission you are changing. Invery simple form this would be:

    chmod 755 filenameThe example above will grant you full rights, group rights to

    execute and read, and all others access to execute the file.

    # Permission

    7 full

    6 read and write

    5 read and execute

    4 read only

    3 write and execute

    2 write only1 execute only

    0 noneStill confused? Use the table above to define the settings for

    the three "users." In the command, the first number refers to

    your permissions, the second refers to group, and the third

    refers to general users.

  • 8/6/2019 linux_RV

    37/46

    Typing the command: chmod 751filename

    gives you full access, the group read and execute, and allothers execute only permission.

    cp Type cp followed by the name of an existing file and the name of

    the new file.

    Ex:

    cp newfile newerfile

    To copy a file to a different directory (without changing th

    e files name), specify the directory instead of the new

    filename. Ex:

    cp newfile testdir

    To copy a file to a different directory and create a new file

    name, you need to specify a directory/a new file name. Ex:

    cp newfile testdir/newerfilecp newfile ../newerfile

    The .. represents one directory up in the hierarchy.

    file Type file followed by the name of an existing file in thedirectory.

    Ex:

    file emergency3_demo.exe

    OUTPUT: MS-DOS executable (EXE)

    This command allows you to figure out what the file type is and

    how to use it. For instance the command will tell you whether it

    is an executable, a compressed file and which type, or something

    unusual.

    This command is simplistic, but often can allow you to determine

    why a file does not respond the way you expect.

    mv Typemv followed by the current name of a file and the new nameof the file.

    Ex:mv oldfile newfile

    Type mv followed by the name of a file and the new directory

    where you'd like to place the file. Ex:

    mv newfile testdir

    This moves the file named newfile to an existing directory named

    testdir. Be certain youre specifying a directory name or the mv

  • 8/6/2019 linux_RV

    38/46

    command alters the name of the file instead of moving it.

    rm Type rmfollowed by the name of a file to remove the file.

    Ex:

    rm newfile

    Use the wildcard character to remove several files at once. Ex:

    rm n*

    This command removes all files beginning with n.

    Type rm -i followed by a filename if youd like to be prompted

    before the file is actually removed. Ex:

    rm -i newfile

    rm -i n*

    By using this option, you have a chance to verify the removal of

    each file. The -i option is very handy when removing a number of

    files using the wildcard character *.

    Manipulating Directories and FilesIf you're a beginner, it may help you to type the command ls -alt to list all of your current files

    and directories. Type ls -altafter you try each command below to be certain it worked properly.

    Directory Related Commands

    Command Summary Use

    cd Use cd to change directories. Type cd followed by the name of a

    directory to access that directory. Keep in mind that you are

    always in a directory and can navigate to directories

    hierarchically above or below. Ex:cd games

    If the directory games is not located hierarchically below the

    current directory, then the complete path must be

    written out. Ex:

    cd /usr/games

    To move up one directory, use the shortcut command. Ex:

    cd ..

    Use cp -r to copy a directory and all of its contents

    Type cp -r followed by the name of an existing directory and the

    name of the new directory. Ex:

    cp -r testing newdirYou must include the -r or youll see the following message:

    cp: testing is a directory and -r not specified.

    This command saves you time if you need to make a mirror image

    of a directory packed with files.

    mkdir Use mkdir to make/create a brand new directory

    Type mkdir followed by the name of a directory. Ex:

  • 8/6/2019 linux_RV

    39/46

    mkdir testdir

    mv Use mv to change the name of a directory

    Type mv followed by the current name of a directory and the new

    name of the directory. Ex:

    mv testdir newnamedir

    pwd

    Trying to find out where on your Linux server you currently arelocated? The pwd (print working directory) command will show you

    the full path to the directory you are currently in. This is

    very handy to use, especially when performing some of the other

    commands on this page!

    rmdir Use rmdir to remove an existing directory (assuming you have

    permissions set to allow this).

    Type rmdir followed by a directory's name to remove it. Ex:

    rmdir testdir

    You CAN'T remove a directory that contains files with this

    command. A more useful command is rm -r that removes directories

    and files within the directories. You can read more about thisin Commands for Beginning Admins

    The rmdir command is used mostly to remove empty directories. If

    you have a desire to use this command then you'll need to delete

    or move the files before attempting to remove a full directory.

    For more help please read the mv command and also File Related

    Commands.

    Command Summary Use

    du

    The du command prints a summary of the amount of information you

    have stored in your directories on the mounted disks.syntax: du [options] path

    ex: du -a /News

    Options:

    -s print the sum of bytes in your directories

    -a print a line for each file in your directory

    grep

    The grep command searches text files for a particular word or

    string of words. Very helpful when trying to find that needle in

    a haystack, like a particular line in a large log file.

    syntax: grep textstring filename(s)

    ex: grep century history.text.doc

    Head

    Tail

    head: prints the beginning of a text file

    tail: prints the end of a text file

    These commands allow you to view parts of a text file.

    tail -n 5 textfile.txt

    head -n 5 textfile.txt

    The examples above will print the last 5 lines of the file

    textfile.txt and then the first 5 lines.

    http://www.reallylinux.com/docs/admin.shtmlhttp://www.reallylinux.com/docs/files.shtmlhttp://www.reallylinux.com/docs/files.shtmlhttp://www.reallylinux.com/docs/admin.shtmlhttp://www.reallylinux.com/docs/files.shtmlhttp://www.reallylinux.com/docs/files.shtml
  • 8/6/2019 linux_RV

    40/46

    locate

    Trying to find out where on your Linux server a particular file

    resides? Having a real nasty time doing it? If you have the Bash

    shell you can try using the locate command to identify where it

    is on your mounted drives.

    Type: locate filename and press enter. Replace filename with the

    name of the file you are looking for. This is a real time saving

    command as you start navigating your Linux server!

    If locate does not work for you try using which.

    Nice

    Nohup

    Nice: runs programs/commands at a lower system priority

    Nohup: runs nice programs even when youre logged off the system

    By using the two commands simultaneously, your large processes

    can continue to run, even when you have logged off the system

    and are relaxing.

    Ex: nice nohup c program.c .

    This command will allow the c compiler to compile program.c even

    when you have logged off the system.

    ps

    related

    to

    "stopped

    jobs"

    The ps command displays all of the existing processes. This

    command is also directly linked to issues with stopped processes(also known as "stopped jobs").

    Occasionally, you may see the message There are Stopped Jobs.

    If you log off the system without properly stopping your jobs,

    some jobs/processes may remain in memory tying up the system and

    drawing unnecessary processing bandwidth.

    Type ps and hit enter. This will list all of your current

    processes running, or stopped.

    PID TT STAT TIME COMMAND

    23036 pl S 0:00 -csh

    23070 pl R 0:00 vi

    The number under PID is the process identification number. To

    kill a process that is stopped, type: kill pid. Replace pid with

    the exact number of the process.

    Ex: While in Vi, you accidentally press the wrong keys. Vi's

    operation is stopped and you are kicked back to the prompt. To

    kill the stopped Vi command, you may type: kill 23070.

    stty

    The stty command allows you to view a listing of your current

    terminal options. By using this command, you can also remap

    keyboard keys, tailoring to your needs.

    Ex: stty and hit enter. This lists your terminal settings.Ex: stty erase\^h . This remaps your erase key (backspace) to

    the Ctrl and h keys. From now on, holding down Ctrl and pressing

    h will cause a backspace. So you're scratching your head asking

    why is this handy? You'll see at some point how stty is also

    used for a number of other useful settings.

    talk In order to contact someone who is on the system, at the prompt

    you type: talk accountname . Replace accountname with the full

  • 8/6/2019 linux_RV

    41/46

    account name of the person. If you dont want anyone to disturb

    you using the talk command, at the prompt

    type: mesg n. This prevents others from using talk to reach you.

    tar

    also

    related

    to gzip

    You're bound to come across files that are g-zipped and tarred.

    Okay, now what? These are methods of compressing and storing

    directories and files in a single "file." Most new Linuxprograms come off the web as something like coolnew-game.4-4-

    01.gz. This file is likely a tar file that has then been gzipped

    for compression. The way to handle these files is simple, but

    requires that you put the file into an appropriate directory. In

    other words, don't plop the file in your root or /bin unless it

    belongs there.

    Now you can do a one fell swoop un-gzip it and untar it into its

    original form (usually multiple files in many sub directories)

    by typing: tar -xvzf *.gz

    This will programmatically un-gzip and then untar all files in

    the current directory into their full original form includingsub-directories etc. Please be careful where and how you run

    this!

    w

    This command allows you to list all users and their processes

    who are currently logged in to the Linux server, or a particular

    users processes. Type: w to view all users processes. Type: w

    jsmith to view jsmiths processes. We use this all the time from

    a system admin standpoint. Please also see more commands to get

    user information on this page. You need to know who logs on to

    your system! Okay, so you have a stand alone Linux box and no

    one else uses it? Try this command just to be sure. ;)

    !!

    Dont waste time and energy retyping commands at the prompt.Instead, use the ! option. To automatically re-display the last

    command you typed at the prompt, type: !! and press enter. Press

    again to invoke the command. You can also automatically re-

    display a command you typed earlier by using the ! and the first

    few letters of the command.

    Ex: At the Linux prompt you had typed the command clear,

    followed by the command pico, followed by the command ftp. In

    order to re-display the clear command you type: !cl and press

    enter. In order to re-display the last command you typed, simply

    type: !! . Try it out. Youll find this a time saver when

    dealing with long commands. Especially commands like tar!

    LINUX TEXT EDITORS

    The vi editor comes with every version of Linux or Unix. Using vi is similar to usingother editors in that you can see your file on the screen (this is not the case with aline editor, for example), move from point to point in the file, and make changes. But

    http://www.reallylinux.com/docs/admin.shtmlhttp://www.reallylinux.com/docs/admin.shtml
  • 8/6/2019 linux_RV

    42/46

    that's where the similarities end. Cryptic commands, a frustrating user interface, andthe absence of prompts can all drive you up a wall.The hardest thing to understand about vi is the concept of modes. When using vi,you're always in either Command or Input mode. In Command mode, you can movethe cursor, search for characters, and delete existing text. But to enter or edit newtext, you have to switch to Input mode. When you start vi, you're in Command mode.To enter Input mode, type the lettera (lowercase only) to signal that you want to addtext after the cursor position. Press esc to switch back to Command mode at anytime.

    Here's how to create a file from scratch using vi. To start, create a new file namedcow.joke by typing

    vi cow.joke

    You'll see a screen that looks like this:

    |

    ~

    ~

    ~

    ~

    ~

    ~

    ~

    ~

    ~

    "cow.joke" [New file]

    Adding New Text to Your File

    Your cursor (the vertical bar at the top of the figure below is in the upper-left corner ofthe screen, and the message at the bottom tells you that a new file called cow.joke

  • 8/6/2019 linux_RV

    43/46

    was just created. The tilde characters in the first column are just placeholders forempty lines.

    Now press the lettera to enter Input mode and type the lines shown in here. Pressenterat the end of each line to go on to the next.

    Jane: Knock, knock...

    Bill: Who's there?

    Jane: The Interrupting Cow.

    Bill: The Interrupting Cow wh...

    Jane: MOOOOOO!

    |

    ~

    ~

    ~

    ~

    "cow.joke" [New file]

    Saving Your Work

    So far, so good--let's save this little masterpiece. You're still in Input mode, so pressesc to enter Command mode; then type ZZ (to put your file to sleep). You won't seeany Z's on the screen, but after you've entered the second Z, your file will disappear,your Linux command prompt will return, and you'll see this message, indicating thatyour file was successfully saved:

    "cow.joke" 6 lines, 113 characters.

    Congratulations--you've just survived your first encounter with vi. You know that the acommand switches to Input mode, esc gets you back to Command mode, and ZZsaves the file, but you'll have to expand this limited repertoire to get any real workdone.

  • 8/6/2019 linux_RV

    44/46

    Common vi Commands

    Have a look at this list of common vi commands (there are many more, but these willat least allow you to get some basic work done). Then we'll do one more exercisebefore moving on.

    Note: As with all of Linux, vi commands are case sensitive.

    Positioning the Cursor

    Move cursor one space right.

    Move cursor one space left.

    Move cursor up one line.

    Move cursor down one line.

    ctrl-F Move forward one screen.ctrl-B Move backward one screen.

    $ Move cursor to end of line.

    ^ Move cursor to beginning of line.

    :1 Move to first line of file

    :$ Move to last line of file

    / Search for a character string.

    ? Reverse search for a character string.

    x Delete the character at the cursor position.dd Delete the current line.

    p Paste data that was cut with x or dd commands.

    u Undo.

    Entering Input Mode

    a Add text after the cursor.

    i Insert text before the cursor.

    R Replace text starting at the cursor.

    o Insert a new line after the current one.Entering Command Mode

    esc Switch from Input mode to Command mode.Exiting or Saving Your File

    :w Write file to disk, without exiting editor.

  • 8/6/2019 linux_RV

    45/46

    ZZ Save the file and exit.

    :q! Quit without saving.

    Trying Out Some vi Commands

    Here's another example to try out some of the vi commands. Enter the followingcommand to fire up vi again, and you should see the file as we left it in the lastexample:

    vi cow.joke

    Changing Text

    Let's change Bill's name to Biff on the second line. To do so, use the arrow keys toposition your cursor on the third character of line 2 (the letter "l"in Bill); then press x

    twice (to delete the two l's). Now press i (to enter Input mode) and then type fftocomplete the change from Bill to Biff.

    Tip: Be careful about pressing the arrow keys while you're in Input mode. In someversions of vi you can position the cursor only in Command mode.

    You could also have used the R command to do this job of replacing text, so use it tochange the other Bill now. Press esc to enter Command mode; then type/Bill tosearch for the word Bill. The cursor should move to line 4, right to where Bill islocated. Now position your cursor on the third character (the letter "l"), press R to

    replace the characters, and type ff. Both Bills should now be Biffs.

    Adding and Deleting Lines

    Here's how to add or delete a line. Press esc to enter Command mode; then pressthe o key to add a new line. You're in Input mode again, so you can type whateveryou like on this new line. But that would ruin the joke, so delete this new line bypressing esc and then entering the dd command. The line you just added should goaway.

    Quitting without Saving Your Changes

    Hmmm. . . . "Biff" just doesn't have that wholesome ring to it, so let's forget about allthe changes we've made in this editing session and exit vi without saving the file.Make sure you're in Command mode, enter the :q! command, and then press enter.Your Linux prompt should return, and the cow.joke file will be just as it was before.

  • 8/6/2019 linux_RV

    46/46

    Parting Words about vi

    Using vi can be frustrating, but it really isn't rocket science once you get used to theconcept of the two modes and get the hang of when it's okay to move your cursor orenter text. If you're ever unsure about which mode you're in, simply press esc once ortwice, and you can be sure you're in Command mode.

    There are some powerful (but arcane) commands that diehard vi users use to getthings done quickly in this relic-of-the-sixties text editor. The man vi command will tellyou a lot more about vi if you decide you want to become proficient.