(Amrood) $ Ls - L:: Unix Commands
(Amrood) $ Ls - L:: Unix Commands
: List name of user currently logged into the system List name of users currently logged to the server. List name of users currently logged to the server with extra info.
Here is the information about all the listed columns: 1. 2. 3. 4. 5. 6. 7. First Column: represents file type and premission given on the file. Below is the description of all type of files. Second Column: represents the number of memory blocks taken by the file or directory. Third Column: represents owner of the file. This is the Unix user who created this file. Fourth Column: represents group of the owner. Every Unux user would have an associated group. Fifth Column: represents file size in bytes. Sixth Column: represents date and time when this file was created or modified last time. Seventh Column: represents file or directory name.
In the ls -l listing example, every file line began with a d, -, or l. These characters indicate the type of file that's listed. Prefix b c d l p s Description Regular file, such as an ASCII text file, binary executable, or hard link. Block special file. Block input/output device file such as a physical hard drive. Character special file. Raw input/output device file such as a physical hard drive Directory file that contains a listing of other files and directories. Symbolic link file. Links on any regular file. Named pipe. A mechanism for interprocess communications Socket used for interprocess communication.
Meta Characters:
* and ? are metacharacters. We use * to match 0 or more characters, a question mark ? matches with single character.
: Displays all the files whose name start with ch and ends with
.doc:
: Here * works as meta character which matches with any character. If you want to display all the files ending with just .doc then you can use above command:
Creating Files:
You can use vi editor to create ordinary files on any Unix system. You simply need to give following command:
[amrood]$ vi filename
Above command would open a file with the given filename. You would need to press key i to come into edit mode. Once you are in edit mode you can start writing your content in the file as below:
This is unix file....I created it for the first time..... I'm going to save this content in this file.
Once you are done, do the following steps:
Press key esc to come out of edit mode. Press two keys Shift + ZZ together to come out of the file completely.
Now you would have a file created with filemame in the current directory.
Editing Files:
You can edit an existing file using vi editor. We would cover this in detail in a separate tutorial. But in short, you can open existing file as follows:
[amrood]$ vi filename
Once file is opened, you can come in edit mode by pressing key i and then you can edit file as you like. If you want to move here and there inside a file then first you need to come out of edit mode by pressing key esc and then you can use following keys to move inside a file:
l key to move to the right side. h key to move to the left side. k key to move up side in the file. j key to move down side in the file.
So using above keys you can position your cursor where ever you want to edit. Once you are positioned then you can use i key to come in edit mode. Edit the file, once you are done press esc and finally two keys Shift + ZZ together to come out of the file completely.
[amrood]$ cat filename This is unix file....I created it for the first time..... I'm going to save this content in this file. [amrood]$
You can display line numbers by using -b option along with cat command as follows:
[amrood]$ cat filename -b 1 This is unix file....I created it for the first time..... 2 I'm going to save this content in this file. [amrood]$
4.
You can give multiple files at a time to get the information about those file. Here is simple syntax:
Copying Files:
To make a copy of a file use the cp command. The basic syntax of the command is:
Renaming Files:
To change the name of a file use the mv command. Its basic syntax is:
Deleting Files:
To delete an existing file use the rm command. Its basic syntax is:
[amrood]$ rm filename
Caution: It may be dangerous to delete a file because it may contain useful information. So be careful while using this command. It is recommended to use -i option along with rm command. Following is the example which would completely remove existing file filename:
[amrood]$ rm filename
[amrood]$
You can remove multiple files at a tile as follows:
Listing Directories:
To list the files in a directory you can use the following syntax:
[amrood]$ls dirname
Following is the example to list all the files contained in /usr/local directory:
[amrood]$ls /usr/local X11 ace atalk bin doc etc gimp include info jikes lib man sbin share ami
Creating Directories:
Directories are created by the following command:
[amrood]$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to create. For example, the command:
Creates the directories docs and pub under the current directory.
Removing Directories:
Directories can be deleted using the rmdir command as follows:
Changing Directories:
You can use the cd command to do more than change to a home directory: You can use it to change to any directory by specifying a valid absolute or relative path. The syntax is as follows:
Renaming Directories:
The mv (move) command can also be used to rename a directory. The syntax is as follows:
Read:
Grants the capability to read ie. view the contents of the file.
Write:
Grants the capability to modify, or remove the content of the file.
Execute:
User with execute permissions can run a file as a program.
Read:
Access to a directory means that the user can read the contents. The user can look at the filenames inside the directory.
Write:
Access means that the user can add or delete files to the contents of the directory.
Execute:
Executing a directory doesn't really make a lot of sense so think of this as a traverse permission. A user must have execute access to the bin directory in order to execute ls or cd command.
Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are two ways to use chmod: symbolic mode and absolute mode.
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
Nov 2 00:10
testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you can see the permission changes:
[amrood]$chmod o+wx testfile [amrood]$ls -l testfile -rwxrwxrwx 1 amrood users 1024 [amrood]$chmod u-x testfile [amrood]$ls -l testfile -rw-rwxrwx 1 amrood users 1024 [amrood]$chmod g=r-x testfile [amrood]$ls -l testfile -rw-r-xrwx 1 amrood users 1024
[amrood]$chmod o+wx,u-x,g=r-x testfile [amrood]$ls -l testfile -rw-r-xrwx 1 amrood users 1024 Nov 2 00:10
testfile
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
Nov 2 00:10
testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you can see the permission changes:
[amrood]$ chmod 755 testfile [amrood]$ls -l testfile -rwxr-xr-x 1 amrood users 1024 [amrood]$chmod 743 testfile [amrood]$ls -l testfile -rwxr---wx 1 amrood users 1024 [amrood]$chmod 043 testfile [amrood]$ls -l testfile ----r---wx 1 amrood users 1024
Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:
\n \s \W \w \u \h \# \$
Newline. Current shell environment. Working directory. Full path of the working directory. Current user.s username. Hostname of the current machine. Command number of the current command. Increases with each new command entered. If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $.
The pr Command:
The pr command does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns. Here is the syntax of pr command:
pr option(s) filename(s)
The pr changes the format of the file only on the screen or on the printed copy; it doesn't modify the original file. Following table lists some pr options: Option -k -d -h "header" -t -l PAGE_LENGTH Produces k columns of output Double-spaces the output (not on all pr versions). Takes the next item as a report header. Eliminates printing of header and top/bottom margins. Set the page length to PAGE_LENGTH (66) lines. Default number of lines of text 56. Offset each line with MARGIN (zero) spaces. Set page width to PAGE_WIDTH (72) characters for multiple text-column output only. Description
-o MARGIN -w PAGE_WIDTH
Before using pr, here are the contents of a sample file named food
[amrood]$cat food Sweet Tooth Bangkok Wok Mandalay Afghani Cuisine Isle of Java Big Apple Deli Sushi and Sashimi Tio Pepe's Peppers ........ [amrood]$
Let's use pr command to make a two-column report with the header Restaurants:
[amrood]$pr -2 -h "Restaurants" food Nov 7 9:58 1997 Restaurants Page 1 Sweet Tooth Bangkok Wok Mandalay Afghani Cuisine ........ [amrood]$ Isle of Java Big Apple Deli Sushi and Sashimi Tio Pepe's Peppers
-rw-rw-rw-rw-rw-rw-rw-rw-r--rw-rw-r-[amrood]$
1 1 1 1
There are various options which you can use along with grep command: Option -v -n -l -c -i Description Print all lines that do not match pattern. Print the matched line and its line number. Print only the names of files with matching lines (letter "l") Print only the count of matching lines. Match either upper- or lowercase.
Next, let's use a regular expression that tells grep to find lines with "carol", followed by zero or more other characters abbreviated in a regular expression as ".*"), then followed by "Aug". Here we are using -i option to have case insensitive search:
[amrood]$ls -l | grep -i "carol.*aug" -rw-rw-r-1 carol doc 1605 Aug 23 07:35 macros [amrood]$
[amrood]$sort food Afghani Cuisine Bangkok Wok Big Apple Deli Isle of Java Mandalay Sushi and Sashimi Sweet Tooth Tio Pepe's Peppers [amrood]$
The sort command arranges lines of text alphabetically by default. There are many options that control the sorting:
Option -n -r -f +x
Description Sort numerically (example: 10 will sort after 2), ignore blanks and tabs. Reverse the order of sort. Sort upper- and lowercase together. Ignore first x fields when sorting.
More than two commands may be linked up into a pipe. Taking a previous pipe example using grep, we can further sort the files modified in August by order of size. The following pipe consists of the commands ls, grep, and sort:
[amrood]$ls -rw-rw-r--rw-rw-r--rw-rw-rw-rw-rw-rw[amrood]$
-l | grep "Aug" | sort +4n 1 carol doc 1605 Aug 23 1 john doc 2488 Aug 15 1 john doc 8515 Aug 6 1 john doc 11008 Aug 6
This pipe sorts all files in your directory modified in August by order of size, and prints them to the terminal screen. The sort option +4n skips four fields (fields are separated by blanks) then sorts the lines in numeric order.
[amrood]$ls -l | grep "Aug" | sort +4n | -rw-rw-r-- 1 carol doc 1605 Aug 23 -rw-rw-r-- 1 john doc 2488 Aug 15 -rw-rw-rw- 1 john doc 8515 Aug 6 -rw-rw-r-- 1 john doc 14827 Aug 9 . . . -rw-rw-rw- 1 john doc 16867 Aug 6 --More--(74%)
15:56 ch05
The screen will fill up with one screenful of text consisting of lines sorted by order of file size. At the bottom of the screen is the more prompt where you can type a command to move through the sorted text. When you're done with this screen, you can use any of the commands listed in the discussion of the more program.
Following is the example to create a new file testfile if it already does not exist in the current working directory:
[amrood]$vi testfile
As a result you would see a screen something like as follows:
Operation Modes:
While working with vi editor you would come across following two modes: 1. 2. Command mode: This mode enables you to perform administrative tasks such as saving files, executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding and replacing. In this mode, whatever you type is interpreted as a command. Insert mode: This mode enables you to insert text into the file. Everything that's typed in this mode is interpreted as input and finally it is put in the file .
The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode you simply type i. To get out of insert mode, press the Esc key, which will put you back into command mode. Hint: If you are not sure which mode you are in, press the Esc key twice, and then you'll be in command mode. You open a file using vi editor and start type some characters and then come in command mode to understand the difference.
The vi is case-sensitive, so you need to pay special attention to capitalization when using commands. Most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2j moves cursor two lines down the cursor location.
There are many other ways to move within a file in vi. Remember that you must be in command mode (press Esc twice). Here are some more commands you can use to move around the file: Command 0 or | $ Description Positions cursor at beginning of line. Positions cursor at end of line.
w b ( ) E { } [[ ]] n| 1G G nG :n fc Fc H nH M L nL :x
Positions cursor to the next word. Positions cursor to previous word. Positions cursor to beginning of current sentence. Positions cursor to beginning of next sentence. Move to the end of Blank delimited word Move a paragraph back Move a paragraph forward Move a section back Move a section forward Moves to the column n in the current line Move to the first line of the file Move to the last line of the file Move to nth line of the file Move to nth line of the file Move forward to c Move back to c Move to top of screen Moves to nth line from the top of the screen Move to middle of screen Move to botton of screen Moves to nth line from the bottom of the screen Colon followed by a number would position the cursor on line number represented by x
Control Commands:
There are following useful command which you can use along with Control Key: Command CTRL+d CTRL+d CTRL+f CTRL+u CTRL+b CTRL+e CTRL+y Move forward 1/2 screen Move forward 1/2 screen Move forward one full screen Move backward 1/2 screen Move backward one full screen Moves screen up one line Moves screen down one line Description
Moves screen up 1/2 page Moves screen down 1/2 page Moves screen up one page Moves screen down one page Redraws screen
Editing Files:
To edit the file, you need to be in the insert mode. There are many ways to enter insert mode from the command mode: Command i I a A o O Description Inserts text before current cursor location. Inserts text at beginning of current line. Inserts text after current cursor location. Inserts text at end of current line. Creates a new line for text entry below cursor location. Creates a new line for text entry above cursor location.
Deleting Characters:
Here is the list of important commands which can be used to delete characters and lines in an opened file: Command x X dw d^ d$ D dd Description Deletes the character under the cursor location. Deletes the character before the cursor location. Deletes from the current cursor location to the next word. Deletes from current cursor position to the beginning of the line. Deletes from current cursor position to the end of the line. Deletes from the cursor position to the end of the current line. Deletes the line the cursor is on.
As mentioned above, most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2x deletes two character under the cursor location and 2dd deletes two lines the cursor is on. I would highly recommend to exercise all the above commands properly before proceeding further.
Change Commands:
You also have the capability to change characters, words, or lines in vi without deleting them. Here are the relevant commands: Command cc cw r R s S Description Removes contents of the line, leaving you in insert mode. Changes the word the cursor is on from the cursor to the lowercase w end of the word. Replaces the character under the cursor. vi returns to command mode after the replacement is entered. Overwrites multiple characters beginning with the character currently under the cursor. You must use Esc to stop the overwriting. Replaces the current character with the character you type. Afterward, you are left in insert mode. Deletes the line the cursor is on and replaces with new text. After the new text is entered, vi remains in insert mode.
Advanced Commands:
There are some advanced commands that simplify day-to-day editing and allow for more efficient use of vi: Command J << >> ~ ^G U u J Description Join the current line with the next one. A count joins that many lines. Shifts the current line to the left by one shift width. Shifts the current line to the right by one shift width. Switch the case of the character under the cursor. Press CNTRL and G keys at the same time to show the current filename and the status. Restore the current line to the state it was in before the cursor entered the line. Undo the last change to the file. Typing 'u' again will re-do the change. Join the current line with the next one. A count joins that many lines.
Displays current position in the file in % and file name, total number of file. Renames current file to filename. Write to file filename. Opens another file with filename. Changes current working directory to dirname. Use to toggle between two opened files. In case you open multiple files using vi, use :n to go to next file in the series. In case you open multiple files using vi, use :p to go to previous file in the series. In case you open multiple files using vi, use :N to go to previous file in the series. Reads file and inserts it after current line Reads file and inserts it after line n.
The / command searches forwards (downwards) in the file. The ? command searches backwards (upwards) in the file.
The n and N commands repeat the previous search command in the same or opposite direction, respectively. Some characters have special meanings while using in search command and preceded by a backslash (\) to be included as part of the search expression. Character ^ . * $ [ < > Description Search at the beginning of the line. (Use at the beginning of a search expression.) Matches a single character. Matches zero or more of the previous character. End of the line (Use at the end of the search expression.) Starts a set of matching, or non-matching expressions. Put in an expression escaped with the backslash to find the ending or beginning of a word. See the '<' character description above.
The character search searches within one line to find a character entered after the command. The f and F commands search for a character on the current line only. f searches forwards and F searches backwards and the cursor moves to the position of the found character.
The t and T commands search for a character on the current line only, but for t, the cursor moves to the position before the character, and T searches the line backwards to the position after the character.
Set Commands:
You can change the look and feel of your vi screen using the following :set commands. To use these commands you have to come in command mode then type :set followed by any of the following options: Command :set ic :set ai :set noai :set nu :set sw :set ws :set wm Ignores case when searching Sets autoindent To unset autoindent. Displays lines with line numbers on the left side. Sets the width of a software tabstop. For example you would set a shift width of 4 with this command: :set sw=4 If wrapscan is set, if the word is not found at the bottom of the file, it will try to search for it at the beginning. If this option has a value greater than zero, the editor will automatically "word wrap". For example, to set the wrap margin to two characters, you would type this: :set wm=2 Changes file type to "read only" Prints terminal type Discards control characters from input Description
Running Commands:
The vi has the capability to run commands from within the editor. To run a command, you only need to go into command mode and type :! command. For example, if you want to check whether a file exists before you try to save your file to that filename, you can type :! ls and you will see the output of ls on the screen. When you press any key (or the command's escape sequence), you are returned to your vi session.
Replacing Text:
The substitution command (:s/) enables you to quickly replace words or groups of words within your files. Here is the simple syntax:
:s/search/replace/g
The g stands for globally. The result of this command is that all occurrences on the cursor's line are changed.
IMPORTANT:
You must be in command mode to use commands. (Press Esc twice at any time to ensure that you are in command mode.) You must be careful to use the proper case (capitalization) for all commands. You must be in insert mode to enter text.
Shell Prompt:
The prompt, $, which is called command prompt, is issued by the shell. While the prompt is displayed, you can type a command. The shell reads your input after you press Enter. It determines the command you want executed by looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs separate words. Following is a simple example of date command which displays current date and time:
Shell Types:
In UNIX there are two major types of shells: 1. 2. The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $ character. The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:
Bourne shell ( sh) Korn shell ( ksh) Bourne Again shell ( bash) POSIX shell ( sh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he was at AT&T Bell Labs in New Jersey. The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to as "the shell". The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this reason, it is the shell of choice for writing scripts to use on several different versions of UNIX. In this tutorial, we are going to cover most of the Shell concepts based on Borne Shell.
Shell Scripts:
The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by a pound sign, #, describing the steps. There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive amounts of data, files to read and store data, and variables to read and store data, and the script may include functions. Shell scripts and functions are both interpreted. This means they are not compiled. We are going to write a many scripts in the next several tutorials. This would be a simple text file in which we would put our all the commands and several other required constructs that tell the shell environment what to do and when to do it.
Example Script:
Assume we create a test.sh script. Note all the scripts would have .sh extension. Before you add anything else to your script, you need to alert the system that a shell script is being started. This is done using the shebang construct. For example:
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne shell. It's called a shebang because the # symbol is called a hash, and the ! symbol is called a bang. To create a script containing these commands, you put the shebang line first and then add the commands:
#!/bin/bash pwd ls
Shell Comments:
You can put your comments in your script as follows:
#!/bin/bash # Author : Zara Ali # Copyright (c) Tutorialspoint.com # Script follows here: pwd
ls
Now you save the above content and make this script executable as follows:
[amrood]$chmod +x test.sh
Now you have your shell script ready to be executed as follows:
[amrood]$./test.sh
This would produce following result:
unix-directories.htm unix-environment.htm
in current directory you would execute using
available
#!/bin/sh # Author : Zara Ali # Copyright (c) Tutorialspoint.com # Script follows here: echo "What is your name?" read PERSON echo "Hello, $PERSON"
Here is sample run of the script:
[amrood]$./test.sh What is your name? Zara Ali Hello, Zara Ali [amrood]$
Variable Names:
The name of a variable can contain only letters ( a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _). By convention, Unix Shell variables would have their names in UPPERCASE. The following examples are valid variable names:
Defining Variables:
Variables are defined as follows::
variable_name=variable_value
For example:
NAME="Zara Ali"
Above example defines the variable NAME and assigns it the value "Zara Ali". Variables of this type are called scalar variables. A scalar variable can hold only one value at a time. The shell enables you to store any value you want in a variable. For example:
VAR1="Zara Ali"
VAR2=100
Accessing Values:
To access the value stored in a variable, prefix its name with the dollar sign ( $): For example, following script would access the value of defined variable NAME and would print it on STDOUT:
Zara Ali
Read-only Variables:
The shell provides a way to mark variables as read-only by using the readonly command. After a variable is marked read-only, its value cannot be changed. For example, following script would give error while trying to change the value of NAME:
Unsetting Variables:
Unsetting or deleting a variable tells the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you would not be able to access stored value in the variable. Following is the syntax to unset a defined variable using the unset command:
unset variable_name
Above command would unset the value of a defined variable. Here is a simple example:
#!/bin/sh
Variable Types:
When a shell is running, three main types of variables are present:
Local Variables: A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at command prompt. Environment Variables: An environment variable is a variable that is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually a shell script defines only those environment variables that are needed by the programs that it runs. Shell Variables: A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables. Previous tutorial warned about using certain nonalphanumeric characters in your variable names. This is because those characters are used in the names of special Unix variables. These variables are reserved for specific functions. For example, the $ character represents the process ID number, or PID, of the current shell:
[amrood]$echo $$
29949
The following table shows a number of special variables that you can use in your shell scripts: Description The filename of the current script. These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on). The number of arguments supplied to a script. All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2. All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2. The exit status of the last command executed. The process number of the current shell. For shell scripts, this is the process ID under which they are executing. The process number of the last background command.
Variable $0 $n
$# $* $@ $? $$ $!
Command-Line Arguments:
The command-line arguments $1, $2, $3,...$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9 as the arguments to the command. Following script uses various special variables related to command line:
#!/bin/sh echo echo echo echo echo echo "File Name: $0" "First Parameter : $1" "First Parameter : $2" "Quoted Values: $@" "Quoted Values: $*" "Total Number of Paramers : $#"
Here is a sample run for the above script:
[amrood]$./test.sh Zara Ali File Name : ./test.sh First Parameter : Zara First Parameter : Ali Quoted Values: Zara Ali Quoted Values: Zara Ali Total Number of Paramers : 2
Note: Here do...done is a kind of loop which we would cover in subsequent tutorial.
Exit Status:
The $? variable represents the exit status of the previous command. Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful. Some commands return additional exit statuses for particular reasons. For example, some commands differentiate between kinds of errors and will return various exit values depending on the specific type of failure. Following is the example of successful command:
[amrood]$./test.sh Zara Ali File Name : ./test.sh First Parameter : Zara First Parameter : Ali Quoted Values: Zara Ali Quoted Values: Zara Ali Total Number of Paramers : 2 [amrood]$echo $? 0 [amrood]$
Arithmetic Operators. Relational Operators. Boolean Operators. String Operators. File Test Operators.
The Bourne shell didn't originally have any mechanism to perform simple arithmetic but it uses external programs, either awk or the must simpler program expr. Here is simple example to add two numbers:
Total value : 4
There are following points to note down:
There must be spaces between operators and expressions for example 2+2 is not correct, where as it should be written as 2 + 2. Complete expresssion should be enclosed between ``, called inverted commas.
Arithmetic Operators:
There are following arithmatic operators supported by Bourne Shell. Assume variable a holds 10 and variable b holds 20 then: Show Examples Operator + Description Addition - Adds values on either side of the operator Subtraction - Subtracts right hand operand from left hand operand Multiplication - Multiplies values on either side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Assignment - Assign right operand in left operand Equality - Compares two numbers, if both are same then returns true. Not Equality - Compares two numbers, if both are different then returns true. Example `expr $a + $b` will give 30 `expr $a - $b` will give -10
= ==
!=
It is very important to note here that all the conditional expressions would be put inside square braces with one spaces around them, for example [ $a == $b ] is correct where as [$a==$b] is incorrect. All the arithmetical calculations are done using long integers.
Relational Operators:
Bourne Shell supports following relational operators which are specific to numberic values. These operators would not work for string values unless their value is numerics. For example, following operators would work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty". Assume variable a holds 10 and variable b holds 20 then:
Checks if the value of two operands are equal or not, [ $a -eq $b ] is not true. if yes then condition becomes true. Checks if the value of two operands are equal or not, [ $a -ne $b ] is true. if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. [ $a -gt $b ] is not true.
-ne
-gt
-lt
Checks if the value of left operand is less than the [ $a -lt $b ] is true. value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. [ $a -ge $b ] is not true.
-ge
-le
[ $a -le $b ] is true.
It is very important to note here that all the conditional expressions would be put inside square braces with one spaces around them, for example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.
Boolean Operators:
There are following boolean operators supported by Bourne Shell. Assume variable a holds 10 and variable b holds 20 then: Show Examples Operator ! Description This is logical negation. This inverts a true condition into false and vice versa. This is logical OR. If one of the operands is true then condition would be true. Example [ ! false ] is true.
-o
-a
This is logical AND. If both the operands are true then condition would be true otherwise it would be false.
String Operators:
There are following string operators supported by Bourne Shell. Assume variable a holds "abc" and variable b holds "efg" then: Show Examples Operator = Description Example
Checks if the value of two operands are equal or not, [ $a = $b ] is not true. if yes then condition becomes true. Checks if the value of two operands are equal or not, [ $a != $b ] is true. if values are not equal then condition becomes true. Checks if the given string operand size is zero. If it is [ -z $a ] is not true. zero length then it returns true. Checks if the given string operand size is non-zero. If it is non-zero length then it returns true. Check if str is not the empty string. If it is empty then it returns false. [ -z $a ] is not false.
!=
-z
-n
str
[ $a ] is not false.
-c file
[ -b $file ] is false.
condition becomes true. -d file Check if file is a directory if yes then condition becomes true. Check if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true. Checks if file has its set group ID (SGID) bit set if yes then condition becomes true. Checks if file has its sticky bit set if yes then condition becomes true. Checks if file is a named pipe if yes then condition becomes true. Checks if file descriptor is open and associated with a terminal if yes then condition becomes true. Checks if file has its set user id (SUID) bit set if yes then condition becomes true. Checks if file is readable if yes then condition becomes true. Check if file is writable if yes then condition becomes true. Check if file is execute if yes then condition becomes true. Check if file has size greater than 0 if yes then condition becomes true. Check if file exists. Is true even if file is a directory but exists. [ -d $file ] is not true.
-f file
[ -f $file ] is true.
-g file
[ -g $file ] is false.
-k file
[ -k $file ] is false.
-p file
[ -p $file ] is false.
-t file
[ -t $file ] is false.
-u file
[ -u $file ] is false.
-r file
[ -r $file ] is true.
-w file
[ -w $file ] is true.
-x file
[ -x $file ] is true.
-s file
[ -s $file ] is true.
-e file
[ -e $file ] is true.
Most of the if statements check relations using relational operators discussed in previous chapter.
case...esac statement
Unix Shell's case...esac is very similar to switch...case statement we have in other programming languages like C or C++ and PERL etc.
You would use different loops based on dfferent situation. For example while loop would execute given commands until given condition remains true where as until loop would execute until a given condition becomes true. Once you have good programming practice you would start using appropriate loop based on situation. Here while and for loops are available in most of the other programming languages like C, C++ and PERL etc.
Nesting Loops:
All the loops support nesting concept which means you can put one loop inside another similar or different loops. This nesting can go upto unlimited number of times based on your requirement.
Here is an example of nesting while loop and similar way other loops can be nested based on programming requirement:
Syntax:
while command1 ; # this is loop1, the outer loop do Statement(s) to be executed if command1 is true while command2 ; # this is loop2, the inner loop do Statement(s) to be executed if command2 is true done Statement(s) to be executed if command1 is true done
Example:
Here is a simple example of loop nesting, let's add another countdown loop inside the loop that you used to count to nine:
#!/bin/sh a=0 while [ "$a" -lt 10 ] do b="$a" while [ "$b" -ge 0 ] do echo -n "$b " b=`expr $b - 1` done echo a=`expr $a + 1` done # this is loop1 # this is loop2
This will produce following result. It is important to note how echo -n works here. Here -n option let echo to avoid printing a new line character.
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 0 2 1 0 3 2 1 0
So far you have looked at creating loops and working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of the loop. In this tutorial you will learn following two statements used to control shell loops: 1. 2. The break statement The continue statement
Example:
Here is a simple example that uses the while loop to display the numbers zero to nine:
Syntax:
The following break statement would be used to come out of a loop:
break
The break command can also be used to exit from a nested loop using this format:
break n
Here n specifies the nth enclosing loop to exit from.
Example:
Here is a simple example which shows that loop would terminate as soon as a becomes 5:
#!/bin/sh a=0 while [ $a -lt 10 ] do echo $a if [ $a -eq 5 ] then break fi a=`expr $a + 1` done
This will produce following result:
0 1 2 3 4 5
Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and var2 equals 0:
#!/bin/sh for var1 in 1 2 3 do for var2 in 0 5 do if [ $var1 -eq 2 -a $var2 -eq 0 ] then break 2 else echo "$var1 $var2" fi done done
This will produce following result. In the inner loop, you have a break command with the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately from inner loop as well.
1 0 1 5
The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop. This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop.
Syntax:
continue
Like with the break statement, an integer argument can be given to the continue command to skip commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.
Example:
The following loop makes use of continue statement which returns from the continue statement and start processing next statement:
#!/bin/sh NUMS="1 2 3 4 5 6 7" for NUM in $NUMS do Q=`expr $NUM % 2` if [ $Q -eq 0 ] then echo "Number is an even number!!" continue fi echo "Found odd number" done
This will produce following result:
Found odd Number is Found odd Number is Found odd Number is Found odd
number an even number!! number an even number!! number an even number!! number
The shell performs substitution when it encounters an expression that contains one or more special characters.
Example:
Following is the example, while printing value of the variable its substitued by its value. Same time "\n" is substituted by a new line:
Value of a is 10
Value of a is 10\n
Here are following escape sequences which can be used in echo command: Escape \\ \a \b \c \f \n \r \t \v backslash alert (BEL) backspace suppress trailing newline form feed new line carriage return horizontal tab vertical tab Description
Command Substitution:
Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.
Syntax:
The command substitution is performed when a command is given as:
`command`
When performing command substitution make sure that you are using the backquote, not the single quote character.
Example:
Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrate command substitution:
#!/bin/sh DATE=`date` echo "Date is $DATE" USERS=`who | wc -l` echo "Logged in user are $USERS" UP=`date ; uptime` echo "Uptime is $UP"
This will produce following result:
Date is Thu Jul 2 03:59:57 MST 2009 Logged in user are 1 Uptime is Thu Jul 2 03:59:57 MST 2009 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15
Variable Substitution:
Variable substitution enables the shell programmer to manipulate the value of a variable based on its state. Here is the following table for all the possible substitutions: Form ${var} Substitue the value of var. Description
${var:-word}
If var is null or unset, word is substituted for var. The value of var does not change. If var is null or unset, var is set to the value of word. If var is null or unset, message is printed to standard error. This checks that variables are set correctly. If var is set, word is substituted for var. The value of var does not change.
${var:=word} ${var:?message}
${var:+word}
Example:
Following is the example to show various states of the above substitution:
#!/bin/sh echo ${var:-"Variable is not set"} echo "1 - Value of var is ${var}" echo ${var:="Variable is not set"} echo "2 - Value of var is ${var}" unset var echo ${var:+"This is default value"} echo "3 - Value of var is $var" var="Prefix" echo ${var:+"This is default value"} echo "4 - Value of var is $var" echo ${var:?"Print this message"} echo "5 - Value of var is ${var}"
This would produce following result:
Variable is not set 1 - Value of var is Variable is not set 2 - Value of var is Variable is not set 3 - Value of var is This is default value 4 - Value of var is Prefix Prefix 5 - Value of var is Prefix
Output Redirection:
The output from a command normally intended for standard output can be easily diverted to a file instead. This capability is known as output redirection: If the notation > file is appended to any command that normally writes its output to standard output, the output of that command will be written to file instead of your terminal: Check following who command which would redirect complete output of the command in users file.
[amrood]$ cat users oko tty01 ai tty15 ruth tty21 pat tty24 steve tty25 [amrood]$
12 12 12 12 12
If a command has its output redirected to a file and the file already contains some data, that data will be lost. Consider this example:
[amrood]$ echo line 1 > users [amrood]$ cat users line 1 [amrood]$
You can use >> operator to append the output in an existing file as follows:
[amrood]$ echo line 2 >> users [amrood]$ cat users line 1 line 2 [amrood]$
Input Redirection:
Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. As the greater-than character > is used for output redirection, the less-than character < is used to redirect the input of a command. The commands that normally take their input from standard input can have their input redirected from a file in this manner. For example, to count the number of lines in the file users generated above, you can execute the command as follows:
[amrood]$ wc -l users
2 users [amrood]$
Here it produces output 2 lines. You can count the number of lines in the file by redirecting the standard input of the wc command from the file users:
Here Document:
A here document is used to redirect input into an interactive shell script or program. We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script. The general form for a here document is:
[amrood]$wc -l << EOF This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF 3 [amrood]$
You can use here document to print multiple lines using your script as follows:
This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF
This would produce following result:
This is a simple lookup program for good (and bad) restaurants in Cape Town.
The following script runs a session with the vi text editor and save the input in the file test.txt.
#!/bin/sh filename=test.txt vi $filename <<EndOfCommands i This file was created automatically from a shell script ^[ ZZ EndOfCommands
If you run this script with vim acting as vi, then you will likely see output like the following:
[amrood]$ cat test.txt This file was created automatically from a shell script [amrood]$
Redirection Commands:
Following is the complete list of commands which you can use for redirection: Command pgm > file pgm < file pgm >> file n > file n >> file n >& m n <& m << tag | Output of pgm is redirected to file Program pgm reads its input from file. Output of pgm is appended to file. Output from stream with descriptor n redirected to file. Output from stream with descriptor n appended to file. Merge output from stream n with stream m. Merge input from stream n with stream m. Standard input comes from here through next tag at start of line. Takes output from one program, or process, and sends it to another. Description
Note that file descriptor 0 is normally standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR). All the Unix commands come with a number of optional and mandatory options. It is very common to forget complete syntax of these commands. Because no one can possibly remember every Unix command and all its options, there has been online help available since Unix's earliest days. Unix's version of help files are called man pages. If you know any command name but you do not know how to use it, then Man Pages are here to help you at every step.
Syntax:
Here is the simple command to get the detail of any Unix command while working with the system:
$man command
Example:
Now you imagine any command for which you want to get help. Assuming you want to know about pwd then you simply need to use the following command:
$man pwd
The above command would open a help for you which would give you complete information about pwd command. Try it yourself at your command prompt to get more detail on You can get complete detail on man command itself using the following command:
$man man
So finally, I would say that man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system.