Sei sulla pagina 1di 46

TIP 1: All of these commands should work from your command prompt (regardless which shell you're using).

If you need help understanding what the options are, or how to use a command, try adding this to the end of your command: --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, especially when 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

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 the owner 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 those specified here. Either may be omitted, in which case a match is not required for the omitted attribute. -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 processed The following options modify how a hierarchy is traversed when the -R option is also specified. If more than 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 in. permission 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 with Permissions u - 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.

x - Execute or run the file as a program. Numeric Permissions: CHMOD can also to attributed by using Numeric Permissions: 400 read by owner 040 read by group 004 read by anybody (other) 200 write by owner 020 write by group 002 write by anybody 100 execute by owner 010 execute by group 001 execute by anybody ls - Short listing of directory contents -a -d -F -g -i -l -R -t list hidden files list the name of the current directory show directories with a trailing '/' executable files with a trailing '*' show group ownership of file in long listing print the inode number of each file long listing giving details about files and directories list all subdirectories encountered 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 create the 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 before overwriting the file. cp -dpr srcdir destdir Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), file attributes (-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 to the 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.This command must be used before searching for files, however cron runs this command periodically on most systems.locate whereis Lists all files whose names contain the string "whereis". directory.

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 the screen. It works well with piping. whereis - Report all known instances of a command wc - Print byte, word, and line counts bg 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 to discover 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, though the 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; see the 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 program provides 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 or name), or prints a list of available signals. killall program killall - signal program

Kills all processes that are instances of the specified program or sends the specified signal to all processes 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 is operational. 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 -r option 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 online documentation 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 to end 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 is called 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 and numbers. When a long file listing is done, there are 10 characters that are shown on the left that indicate type and permissions of the file. File permissions are shown according to the following syntax example:

drwerwerwe There are a total of 10 characters in this example, as in all Linux files. The first character indicates the type of file, and the next three indicate read, write, and execute permission for each of the three user types, user, group and other. Since there are three types of permission for three users, there are a total of nine 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

2. 3. 4. 5. 6. 7.

p = named pipe - = regular file c= character (unbuffered) device file special b=block (buffered) device file special Links: The number of directory entries that refer to the file. In our example, there are four. The file's owner in our example is George. The group the file belongs to. In our example, the group is team1. The size of the file in bytes 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. The name of the file.
o o o o

Set User Identification Attribute


The file permissions bits include an execute permission bit for file owner, group and other. When the execute bit 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 set group ID bit is set and the user running the program is given access based on access permission for the group the 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 -rwxr-sr-x 1 root 1 root root mail 14024 Sep 9 1999 chfn 12072 Aug 16 1999 lockfile

The files chfn and lockfile are located in the directory "/usr/bin". The "s" takes the place of the normal location 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:

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 with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, 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 for other. The high bit (4) is for read access, the middle bit (2) os for write access, and the low 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.

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 the octal 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. The defaults 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 the default permission value for the file type being created. An example for a text file is shown below with a umask 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 a default with regard to reading, writing, or executing the file. The umask value here means the group the file belongs to and users other than the owner will not be able to write to the file. In this case, when a new text file is created it will have a file permission value of 644, which means the owner can read and write the file, but members 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 $ ls * * $ ls a* Matches any string or group of characters. $ ls *.c $ ls ut*.c Matches any single character. $ ls ? $ ls fo? Examples will show all files will show all files whose first name is starting with letter 'a' will show all files having extension .c will show all files having extension .c but file name must begin with 'ut'. will show all files whose names are 1 character long will show all files whose names are 3 character long and file name begin with fo will show all files beginning with letters a,b,c

[...]

Matches any one of the $ ls [abc]* enclosed characters

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

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 us file name that beginning with a,b,c,e...o, like /bin/ps /bin/pwd /bin/rvi /bin/rview /bin/sleep /bin/touch /bin/sort /bin/true /bin/view /bin/wcomp

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

Pipe Defined as: "A pipe is nothing but a temporary storage place where the output of one command is stored and then passed as 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

$ ls | more $ who | sort $ who | sort > user_list $ who | wc -l $ ls -l | wc -l $ who | grep raju

Output of ls command is given as input to more command So that output is printed one screen full page at a time. Output of who command is given as input to sort command So that it will print sorted list of users Same as above except output of sort is send to (redirected) user_list file Output of who command is given as input to wc command So that it will number of user who logon to system Output of ls command is given as input to wc command So that it will print number of files in current directory. Output of who command is given as input to grep command So that it will print if particular user name if he is logon or nothing is printed (To see particular user is logon or not)

Linux Command Related with Process


Following tables most commonly used command(s) with process: For this purpose To see currently running process To stop any process by PID i.e. to kill process To stop processes by name i.e. to kill process To get information about all running process To stop all process except your shell For background processing (With &, use to put particular command and program in background) To display the owner of the processes along with the processes Use this Command ps kill {PID} killall {Process-name} ps -ag kill 0 linux-command & ps aux Examples* $ ps $ kill 1012 $ killall httpd $ ps -ag $ kill 0 $ ls / -R | wc -l & $ ps aux For e.g. you want to see whether Apache web server process is running or not then give command $ ps ax | grep httpd $ top
Note that to exit from top command press q.

To see if a particular process is running or not. For this ps ax | grep process-Upurpose you have to use ps command in combination with want-to see the grep command

To see currently running processes and other information top like memory and CPU usage with real time updates. To display a tree of processes pstree * To run some of this command you need to be root or equivalnt user.

$ pstree

Answer to Process Section.

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 you will verify this? Ans.: No its not true, when you start Linux Os, various process start in background for different purpose. To verify this simply use top or ps aux command. 4) You don't want to listen music (MP3 Files) but want to continue with other work on PC, you will take any of the following action: 1. 2. 3. 4. Turn off Speakers Turn off Computer / Shutdown Linux Os Kill the MP3 playing process 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 write special character sequences to console, which control every aspects of the console like Colors on screen, Bold or Blinking text effects, clearing the screen, showing text boxes etc. For this purpose we have to use special code 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 World Above 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 control character) 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 Hello Colorful World!" ) is process as follows

1) First \033, is escape character, which causes to take some action 2) 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 follows Syntax echo -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 as console receives the message it start to process/read it, and if it found escape character (\033) it moves to escape mode, then it read "[" character and moves into Command Sequence Introduction (CSI) mode. In CSI mode console reads a series of ASCII-coded decimal numbers (know as parameter) which are separated by semicolon (;) . This numbers are read until console action letter or character is not found (which determines what action to take). In above example 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 Use in CSI Examples h Set the ANSI mode echo -e "\033[h" l Clears the ANSI mode echo -e "\033[l" Useful to show characters in different colors or effects such as BOLD and m echo -e "\033[35m Hello World" Blink, see below for parameter taken by m. Turns keyboard num lock, caps lock, q echo -e "\033[2q" scroll lock LED on or off, see below. Stores the current cursor x,y position s echo -e "\033[7s" (col , row position) and attributes u Restores cursor position and attributes echo -e "\033[8u" m understand following parameters Parameter 0 1 Meaning Example Sets default color scheme (White foreground and Black background), normal intensity, no blinking etc. Set BOLD intensity $ echo -e "I am \033[1m BOLD \033[0m Person" Character or letter \033

2 5

Set dim intensity Blink Effect Reverse video effect i.e. Black 7 foreground and white background $ echo -e "\033[7m Linux OS! Best OS!! \033[0m" in default color scheme Shows special control character as graphics character. For e.g. Before issuing this command press alt key $ press alt + 178 (hold down it) from numeric key $ echo -e "\033[11m" pad press 178 and leave both key; $ press alt + 178 11 nothing will be printed. Now give $ echo -e "\033[0m" --> command shown in example $ press alt + 178 and try the above, it works. (Hey you must know extended ASCII Character for this!!!) 25 Removes/disables blink effect 27 Removes/disables reverse effect Set foreground color 31 - RED 30 - 37 32 - Green $ echo -e "\033[31m I am in Red" xx - Try to find yourself this left as exercise for you :-) Set background color 40 - 47 xx - Try to find yourself this left as $ echo -e "\033[44m Wow!!!" exercise for you :-) q understand following parameters Parameters 0 1 2 3 Meaning Turns off all LEDs on Keyboard Scroll lock LED on and others off Num lock LED on and others off Caps lock LED on and others off

I am BOLD Person Prints BOLD word in bold intensity and next ANSI Sequence remove bold effect (\033[0m) $ echo -e "\033[1m BOLD \033[2m DIM \033[0m" $ echo -e "\033[5m Flash! \033[0m"

Shell Built in Variables


Shell Built in Variables $# Meaning Number of command line arguments. Useful to test no. of command line args in shell script.

$* $@ $$$ $!

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 is executed. Syntax:
if condition then command1 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 >,<, <> etc) and mathematical operators (such as +, -, / etc )." Following are all examples of expression: 3+6 3 * 65 a<b c > 5 + 30 -1 Type following commands (assumes you have file called foo) $ cat foo $ echo $? The cat command return zero(0) i.e. exit status, on successful, this can be used, in if condition as follows, Write shell script as
$ cat > showfile #!/bin/sh # #Script to print file #

if cat $1 then echo -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 successful and 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 it returns non-zero value (indicates some sort of failure) and this statement echo -e "\n\nFile $1, found and successfully echoed" is skipped by our shell. Exercise Write shell script as follows:
cat > trmif # # Script to test rm command and exist status # if rm $1 then echo "$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

#!/bin/sh # # Script to see whether argument is positive # if test $1 -gt 0 then echo "$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) then test will return 0 and output will printed as 5 number is positive but for -45 argument there is no output because our condition is not true(0) (no -45 is not greater than 0) hence echo statement is skipped. And for last statement we have not supplied any argument hence error ./ispostive: test: -gt: unary operator expected, is generated by shell , to avoid such error we can test whether command line argument is supplied or not. test or [ expr ] works with 1.Integer ( Number without decimal point) 2.File types 3.Character strings For Mathematics, use following operator in Shell Script Mathematical Operator in Shell Script Normal Arithmetical/ Mathematical Statements

Meaning

But in Shell For test statement with if command For [ expr ] statement with if command if [ 5 -eq 6 ] if [ 5 -ne 6 ] if [ 5 -lt 6 ] if [ 5 -le 6 ]

-eq -ne -lt -le

is equal to is not equal to is less than is less than or equal to

5 == 6 5 != 6 5<6 5 <= 6

if test 5 -eq 6 if test 5 -ne 6 if test 5 -lt 6 if test 5 -le 6

-gt

is greater than 5 > 6 is greater than -ge 5 >= 6 or equal to NOTE: == is equal, != is not equal.

if test 5 -gt 6 if test 5 -ge 6

if [ 5 -gt 6 ] if [ 5 -ge 6 ]

For string Comparisons use Operator string1 = string2 string1 != string2 string1 -n string1 -z string1 Meaning string1 is equal to string2 string1 is NOT equal to string2 string1 is NOT NULL or not defined string1 is NOT NULL and does exist string1 is NULL and does exist Shell also test for file and directory types Meaning Non empty file Is File exist or normal file and not a directory Is Directory exist and not a file Is writeable file Is read-only file Is file is executable Logical Operators

Test -s file -f file -d dir -w file -r file -x file

Logical operators are used to combine two or more condition at a time Operator ! expression expression1 -a expression2 expression1 -o expression2 Meaning Logical NOT Logical AND Logical OR

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

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

else

if condition is not true then execute 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 ] then echo "$0 : You must give/supply one integers" exit 1 fi if test $1 -gt 0 then echo "$1 number is positive" else echo "$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 ($#) passed to script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false and if no command 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 script 2 will print this error message And finally statement exit 1 causes normal program termination with exit status 1 (nonzero means script is not successfully run).

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 if test $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 else statement. This is called the nesting of ifs.
$ vi nestedif.sh osch=0 echo echo echo read "1. Unix (Sun Os)" "2. Linux (Red Hat)" -n "Select your os choice [1 or 2]? " 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 ] ; then echo "You Pick up Linux (Red Hat)" else echo "What you don't like Unix/Linux OS." fi

fi

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.

Note that Second if-else constuct is nested in the first else statement. If the condition in the first if statement is false the the condition in the second if statement is checked. If it is false as well the final else statement is executed. You can use the nested ifs as follows also: Syntax:
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi

Multilevel if-then-else
Syntax:
if condition then condition is zero (true - 0) execute all commands up to elif statement elif condition1 then condition1 is zero (true - 0) execute all commands up to elif statement elif condition2 then condition2 is zero (true - 0) execute all commands up to elif statement else None 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:

$ cat > elf # #!/bin/sh # Script to test if..elif...else # if [ $1 -gt 0 ]; then echo "$1 is positive" elif [ $1 -lt 0 ] then echo "$1 is negative" elif [ $1 -eq 0 ] then echo "$1 is zero" else echo "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 expected Opps! a is not number, give number Above 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 of instruction 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.

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 > testfor for i in 1 2 3 4 5 do echo "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 shell execute echo statement for each assignment of i. (This is usually know as iteration) This process will continue until all the items in the list were not finished, because of this it will repeat 5 echo statements. To make you idea more clear try following script:
$ cat > mtable #!/bin/sh # #Script to test for loop # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" echo "Use to print multiplication table for given number" exit 1 fi n=$1 for i in 1 2 3 4 5 6 7 8 9 10 do echo "$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 as 7*1=7 7 * 2 = 14 ... ..

7 * 10 = 70 And 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, Hence script is showing Error message, Syntax and usage of our script. This is good idea if our program takes some argument, 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 and therefore script is terminated) Even you can use following syntax: Syntax:
for (( expr1; expr2; expr3 )) do ..... ... repeat all statements between do and done until expr2 is TRUE Done

In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. All the statements between do and done is executed repeatedly UNTIL the value of expr2 is TRUE. AFTER each iteration of the loop, expr3 is evaluated. This is usually use to increment a loop counter.
$ cat > for2 for (( i = 0 ; i <= 5; i++ do echo "Welcome $i times" done

))

Run the above script as follows: $ chmod +x for2 $ ./for2 Welcome 0 times Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times

Nesting of for Loop


As you see the if statement can nested, similarly loop statement can be nested. You can nest the for loop. To understand the nesting of for loop see the following shell script.

$ vi nestedfor.sh for (( i = 1; i <= 5; i++ )) do

### Outer for loop ###

for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ### do echo -n "$i " done echo "" #### print the new line ### done

Run the above script as follows: $ chmod +x nestedfor.sh $ ./nestefor.sh 11111 22222 33333 44444 55555 Here, for each value of i the inner loop is cycled through 5 times, with the varible j taking values from 1 to 5. The inner for loop terminates when the value of j exceeds 5, and the outer loop terminets when the value of i exceeds 5. Following script is quite intresting, it prints the chess board on screen.
$ vi chessboard for (( i = 1; i <= 9; i++ )) ### Outer for loop ### do for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ### do tot=`expr $i + $j` tmp=`expr $tot % 2` if [ $tmp -eq 0 ]; then echo -e -n "\033[47m " else echo -e -n "\033[40m " fi done echo -e -n "\033[40m" #### set back background colour to black echo "" #### print the new line ### done

Run the above script as follows: $ chmod +x chessboard $ ./chessboard On my terminal above script produec the output as follows:

Above shell script cab be explained as follows: Command(s)/Statements for (( i = 1; i <= 9; i++ )) do for (( j = 1 ; j <= 9; j++ )) do tot=`expr $i + $j` tmp=`expr $tot % 2` if [ $tmp -eq 0 ]; then echo -e -n "\033[47m " else echo -e -n "\033[40m " fi done echo -e -n "\033[40m" echo "" done Explanation Begin the outer loop which runs 9 times., and the outer loop terminets when the value of i exceeds 9 Begins the inner loop, for each value of i the inner loop is cycled through 9 times, with the varible j taking values from 1 to 9. The inner for loop terminates when the value of j exceeds 9. See for even and odd number positions using these statements. If even number posiotion print the white colour block (using echo -e -n "\033[47m " statement); otherwise for odd postion print the black colour box (using echo -e -n "\033[40m " statement). This statements are responsible to print entier chess board on screen with alternet colours. End of inner loop Make sure its black background as we always have on our terminals. Print the blank line End of outer loop and shell scripts get terminted by printing the chess board.

What Are Regular Expressions


A regular expression is a formula for matching strings that follow some pattern. Regular expressions are supported by many text editors, class libraries such as Rogue Wave's Tools.h++, scripting tools such as awk, grep, sed, and

increasingly in interactive development environments such as Microsoft's Visual C++. Regular expressions are made up of normal characters and metacharacters. Normal characters include upper and lower case letters and digits. The metacharacters have special meanings and are described in detail below. In the simplest case, a regular expression looks like a standard search string. For example, the regular expression "testing" contains no metacharacters. It will match "testing" and "123testing" but it will not match "Testing". The table below lists metacharacters and a short explanation of their meaning. Metacharact Description er
.

[ ] [c1-c2] [^c1-c2]

Matches any single character. For example the regular expression r.t would match the strings rat, rut, r t, but not root. Matches the end of a line. For example, the regular expression weasel$ would match the end of the string "He's a weasel" but not the string "They are a bunch of weasels." Matches the beginning of a line. For example, the regular expression ^When in would match the beginning of the string "When in the course of human events" but would not match "What and When in the" . Matches zero or more occurences of the character immediately preceding. For example, the regular expression .* means match any number of any characters. This is the quoting character, use it to treat the following character as an ordinary character. For example, \$ is used to match the dollar sign character ($) rather than the end of a line. Similarly, the expression \. is used to match the period character rather than any single character. Matches any one of the characters between the brackets. For example, the regular expression r[aou]t matches rat, rot, and rut, but not ret. Ranges of

\< \>

\( \)

\{i,j\}

\{i\}

characters can specified by using a hyphen. For example, the regular expression [0-9] means match any digit. Multiple ranges can be specified as well. The regular expression [A-Za-z] means match any upper or lower case letter. To match any character except those in the range, the complement range, use the caret as the first character after the opening bracket. For example, the expression [^269A-Z] will match any characters except 2, 6, 9, and upper case letters. Matches the beginning (\<) or end (\>) or a word. For example, \<the matches on "the" in the string "for the wise" but does not match "the" in "otherwise". NOTE: this metacharacter is not supported by all applications. Treat the expression between \( and \) as a group. Also, saves the characters matched by the expression into temporary holding areas. Up to nine pattern matches can be saved in a single regular expression. They can be referenced as \1 through \9. Or two conditions together. For example (him|her) matches the line "it belongs to him" and matches the line "it belongs to her" but does not match the line "it belongs to them." NOTE: this metacharacter is not supported by all applications. Matches one or more occurences of the character or regular expression immediately preceding. For example, the regular expression 9+ matches 9, 99, 999. NOTE: this metacharacter is not supported by all applications. Matches 0 or 1 occurence of the character or regular expression immediately preceding.NOTE: this metacharacter is not supported by all applications. Match a specific number of instances or instances within a range of the preceding character. For example, the expression A[0-9]\{3\} will match "A" followed by exactly 3 digits. That is, it will match A123 but not A1234. The expression [0-9]\{4,6\} any sequence of 4, 5, or 6 digits. NOTE: this metacharacter is not supported by all applications.

The simplest metacharacter is the dot. It matches any one character (excluding the newline character). Consider a file named test.txt consisting of the following lines:
he is a rat he is in a rut the food is Rotten I like root beer

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

searches for the regular expression r.t in each line of test.txt and prints the matching lines. The regular expression r.t matches an r followed by any character 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 upper and lower the square brackets (character range metacharacters) can be used. The regular expression [Rr] matches either R or r. So, to match an upper or lower case r followed by any character followed by the character t the regular expression [Rr].t will do the trick.

Simple Examples
Here are a few representative, simple examples. vi command
:%s/ */ /g :%s/ *$// :%s/^/ / :%s/^[0-9][0-9]* // :%s/b[aeio]g/bug/g :%s/t\([aou]\)g/h\1t/g

What it does Change 1 or more spaces into a single space. Remove all spaces from the end of the line. Insert a space at the beginning of every line. Remove all numbers at the beginning of a line. Change all occurences of bag, beg, big, and bog, to bug. Change all occurences of tag, tog, and tug to hat, hot, and hug 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 any parameters supplied to foo(). That is, we must be able to make changes like the following:

Before
foo(10,7,2) foo(x+13,y-2,10) foo( bar(8), x+y+z, 5)

After
foo(7,10,2) foo(y-2,x+13,10) 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 this expression is to identify invocations of foo() with three parameters between the parentheses. 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 which \([^,]*\), are followed by a comma. The non-comma characters are tagged. Why would we use an expression like [^,]*, instead of something more straightforward like .*, to match the first parameter? Consider applying the pattern .*, to the string "10,7,2". Should it match "10," or "10,7," ? To resolve this ambiguity, regular expressions will always match the longest string possible. In this case "10,7," which covers two parameters instead of one parameter like we want. So, by using the expression [^,]*, we force the pattern to match all characters up to the first comma.
[^,]

The expression up to this point is: foo(\([^,]*\), and can be roughly translated as "after you find foo( tag all characters up to the next comma as \1". We tag the second parameter just like the first and it can be referenced as \2. The tag used on the third parameter is exactly like the others except that we search for all characters up to the right parenthesis. This pattern guarantees that we update only those instances of foo() where 3 parameters are specified. In these times of function and method overloading, being explicit often proves to be useful. In the substitution 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 2
We have a CSV (comma separated value) file with information we need, but in the wrong format. The columns of data are currently arranged in the following order: Name, Company Name, State, Postal Code. We need to reorganize the data into the following order in order to use it with a particular piece of software:

Name, State-Postal Code, Company Name. This means that we must change the order of the columns in addition to merging two columns to form a new column value. The particular piece of software that needs this data will not work if there are any whitespace characters (spaces or tabs) before or after the commas. So we must remove whitespace around the commas. Here are a few lines from the data we have:
Bill Jones, HI-TEK Corporation , CA, 95011 Sharon Lee Smith, Design Works Incorporated, CA, 95012 B. Amos , Hill Street Cafe, CA, 95013 Alexander Weatherworth, The Crafts Store, CA, 95014 ... Bill Jones,CA 95011,HI-TEK Corporation Sharon Lee Smith,CA 95012,Design Works Incorporated B. Amos,CA 95013,Hill Street Cafe Alexander Weatherworth,CA 95014,The Crafts Store ...

We need to transform them to look like this:

We'll look at two regular expressions to solve this problem. The first moves the columns 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: The approach is similar to that of Example 1. The Name is matched by the expression \([^,]*\), that is, all characters up to the first comma. The name can then be referenced as \1 in the replacement pattern. The Company Name and State fields are matched just like the Name field and are referenced as \2 and \3 in 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 in the 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] :%s/\([^,]*\),\([^,]*\),\([^,]*\),\(.*\)/\1,\3 \4,\2/

matches a space or tab character; [ \t]* matches 0 or more spaces or tabs; [ \t]*, matches 0 or more spaces or tabs followed by a comma; and finally [ \t]*,[ \t]* matches 0 or more spaces or tabs followed by a comma followed by 0 or more spaces or tabs. In the replacement pattern, we simply replace whatever we matched with a single comma. The optional g parameter is added to the end of the substitution command to apply the substitution to all commas in the line.

Hard Examples (Magical Hieroglyphics)


coming soon.

Regular Expressions In Various Tools

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

sed
Sed 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 called price.txt. sed script Description
sed 's/^$/d' price.txt sed 's/^[ \t]*$/d' price.txt sed 's/"//g' price.txt

removes all empty lines removes all lines containing only whitespace remove all quotation marks

awk
Awk is a programming language which can be used to perform sophisticated analysis and manipulation of text data. For complete details, see the man page awk(1). Its peculiar name is an acronym made up of the first character of its authors last names (Aho, Weinberger, and Kernighan). There are many good awk examples in the book The AWK Programming Language (written by Aho, Weinberger, and Kernighan). Please don't form any broad opinions about awk's capabilities based on the following trivial sample scripts. For purposes of these examples, assume that we're working with a file called price.txt. As with sed, awk simply echos its output to its standard out. awk script
awk '$0 !~ /^$/' price.txt awk 'NF > 0' price.txt awk '$2 ~ /^[JT]/ {print $3}' price.txt awk '$2 !~ /[Mm]isc/ {print $3 + $4}' price.txt awk '$3 !~ /^[0-9]+\.[0-9]*$/ {print $0}' price.txt

Description removes all empty lines a better way to remove all lines in awk print the third field of all lines whose second field begins with 'J' or 'T' for all lines whose second field does not contain 'Misc' or 'misc' print the sum of columns 3 and 4 (assumed to be numbers). 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

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

9. print the entire line if the second field contains 'John' or 'Fred'

Using grep command


The 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 an email recently with his phone number, and you want to call him ASAP to order some books. Instead of launching your email program and sifting through all the messages, you can scan your in-box file, like this:
grep 'number' /var/mail/hermie can 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 organizations

Here, 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 <flags> <pattern> <files>

The most useful grep flags are shown here: -i Ignore uppercase and lowercase when comparing. -v Print only lines that do not match 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 be very 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 more characters). Regular expressions also come into play when using vi, sed, awk, and other Unix commands. If you want to master Unix, take time to understand regular expressions. Here is a sample poem.txt file and some grep commands to demonstrate regular-expression pattern matching:

Mary Mary Jack Jill

had a fried ate a had a

little lamb a lot of spam Spam sandwich lamb spamwich

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

grep 'spam' poem.txt Mary fried a lot of spam Jill had a lamb spamwich
To print all lines containing spam (ignoring uppercase and lowercase), enter

grep Mary Jack Jill

-i 'spam' poem.txt fried a lot of spam ate a Spam sandwich had a lamb spamwich

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 not containing 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 sandwich Jill had a lamb spamwich
To print all lines containing had followed 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 {search files 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 word boundary is either the edge of the line or any character except a letter, digit or underscore "_". To look for if, but skip stiff, the expression is \<if\>. 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 of grep to show you what can be done:

grep '^From: ' /usr/mail/$USER grep '[a-zA-Z]' grep '[^a-zA-Z0-9] grep '[0-9]\{3\}-[0-9]\{4\}' grep '^.$' grep '"smug"' grep '"*smug"*' grep '^\.' grep '^\.[a-z][a-z]'

{list your mail} {any line with at least one letter} {anything not a letter or number} {999-9999, like phone numbers} {lines with exactly one character} {'smug' within double quotes} {'smug', with or without quotes} {any line that starts with a Period "."} {line start with "." and 2 lc letters}

Use passwd to change your current password

Type passwd and press enter. You'll see the message Changing password for 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 new password and press again. Create a secure password that combines parts of words and numbers. For instance, your dog's name may be Rufus. He may have been born in 1980. Create a password that uses parts of both the name and date of birth, such as 80rufuS. Note the use of at least one capital letter. This is a fairly secure password and easy to remember. Type pwd 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 forget which directory youve changed to and are trying to run other commands.

Use pwd to list the name of your current directory

Working With file Manipulating Files


Included in this section are the commands needed to copy, delete, move, and rename files. Security and permissions are also reviewed below in the chmod command. NOTE: All of these commands should work 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
chmod

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

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 drwxr-s--x d-wx-wx-wx drwxr-xr-x 7 reallyli reallyli 1024 Apr 6 14:30 . 22 reallyli reallyli 1024 Mar 30 18:20 .. 3 reallyli reallyli 1024 Apr 6 14:30 content 2 reallyli reallyli 1024 Mar 25 20:43 files

What do the r indicates contents) w indicates contents) x indicates executable) - indicates

letters mean in front of the files/directories mean? that it is readable (someone can view the files that it is writable (someone can edit the files that it is executable (someone can run the file, if 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. In very simple form this would be: chmod 755 filename The 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 only 1 execute only 0 none Still 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.

Typing the command: chmod 751 filename gives you full access, the group read and execute, and all others 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/newerfile cp newfile ../newerfile The .. represents one directory up in the hierarchy.

file

Type file followed by the name of an existing file in the directory. 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

Type mv followed by the current name of a file and the new name of the file. Ex: mv oldfile newfile Type mv followed by where you'd like to mv newfile testdir This moves the file testdir. Be certain

the name of a file and the new directory place the file. Ex: named newfile to an existing directory named youre specifying a directory name or the mv

command alters the name of the file instead of moving it. rm Type rm followed 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 Files


If 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 -alt after you try each command below to be certain it worked properly.

Directory Related Commands


Command cd Summary Use 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 newdir You 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. Use mkdir to make/create a brand new directory Type mkdir followed by the name of a directory. Ex:

mkdir

mv

pwd

rmdir

mkdir testdir 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 Trying to find out where on your Linux server you currently are located? 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! 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 this in 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

du

Summary Use 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 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: 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.

grep

Head Tail

locate

Nice Nohup

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: 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. 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. 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. In order to contact someone who is on the system, at the prompt you type: talk accountname . Replace accountname with the full

ps related to "stopped jobs"

stty

talk

tar also related to gzip

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. 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 Linux programs come off the web as something like coolnew-game.4-401.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 including sub-directories etc. Please be careful where and how you run this! 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 redisplay 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 using other editors in that you can see your file on the screen (this is not the case with a line editor, for example), move from point to point in the file, and make changes. But

that's where the similarities end. Cryptic commands, a frustrating user interface, and the 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 move the cursor, search for characters, and delete existing text. But to enter or edit new text, you have to switch to Input mode. When you start vi, you're in Command mode. To enter Input mode, type the letter a (lowercase only) to signal that you want to add text after the cursor position. Press esc to switch back to Command mode at any time. Here's how to create a file from scratch using vi. To start, create a new file named cow.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 of the screen, and the message at the bottom tells you that a new file called cow.joke

was just created. The tilde characters in the first column are just placeholders for empty lines. Now press the letter a to enter Input mode and type the lines shown in here. Press enter at 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 press esc to enter Command mode; then type ZZ (to put your file to sleep). You won't see any 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 that your file was successfully saved: "cow.joke" 6 lines, 113 characters. Congratulations--you've just survived your first encounter with vi. You know that the a command switches to Input mode, esc gets you back to Command mode, and ZZ saves the file, but you'll have to expand this limited repertoire to get any real work done.

Common vi Commands Have a look at this list of common vi commands (there are many more, but these will at least allow you to get some basic work done). Then we'll do one more exercise before 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.

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 following command to fire up vi again, and you should see the file as we left it in the last example: vi cow.joke Changing Text Let's change Bill's name to Biff on the second line. To do so, use the arrow keys to position 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 ff to complete the change from Bill to Biff. Tip: Be careful about pressing the arrow keys while you're in Input mode. In some versions 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 to change the other Bill now. Press esc to enter Command mode; then type /Bill to search for the word Bill. The cursor should move to line 4, right to where Bill is located. 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 press the o key to add a new line. You're in Input mode again, so you can type whatever you like on this new line. But that would ruin the joke, so delete this new line by pressing esc and then entering the dd command. The line you just added should go away. Quitting without Saving Your Changes Hmmm. . . . "Biff" just doesn't have that wholesome ring to it, so let's forget about all the 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.

Parting Words about vi Using vi can be frustrating, but it really isn't rocket science once you get used to the concept of the two modes and get the hang of when it's okay to move your cursor or enter text. If you're ever unsure about which mode you're in, simply press esc once or twice, and you can be sure you're in Command mode. There are some powerful (but arcane) commands that diehard vi users use to get things done quickly in this relic-of-the-sixties text editor. The man vi command will tell you a lot more about vi if you decide you want to become proficient.

Potrebbero piacerti anche