Vous êtes sur la page 1sur 41

UNIX

Basic Commands
Author: Anand P
Creation date: 23-08-2009
Version: 0.1
Training Level: E0

September 22, 2009 TCS Public


September 22, 2009
Table of Contents
‹ Introduction
‹ Basic Commands
‹ Alias & Unalias Commands
‹ Directory Related commands
‹ File Related Commands
‹ Definition of Shell
‹ Shell Script Vs Functions
‹ Functions
‹ Variables in Unix
‹ Control Structures
‹ Conclusion

September 22, 2009


Introduction
• This training material explains basic UNIX commands. This presentation explains
frequently commands in Unix. This is a very brief introduction to some useful
Unix Commands, including examples of how to use each command.

September 22, 2009


WHO & WHO AM I

• $ who - aa1 tty3a Jun 10 09:15


• aa2 tty3a Jun 10 09:25
• aa3 tty3a Jun 10 08:22

• $ who am I -
• aa1 tty3a Jun 10 09:15

September 22, 2009


Basic Procedure
• If any mistake in commands, press Backspace(Å) to erase characters
• To cancel typed command before press Enter, press Del key
• Ctrl+d to exit from the session

September 22, 2009


Alias & Unalias Commands
•Alias - Defined a new name for a command
•$ alias – with no arguments lists currently active
aliases
•Syntax is; $ alias new command old command
•$ alias cl cal 2003
•$ cl
•Unalias - Removes alias
•Requires an argument.
•Syntax; $ unalias cl

September 22, 2009


Creation of files
• touch – create one or more empty files
• $ touch file file1 file2 – create 3 empty files
• Cat – Create file, write into that file, append already existing file and also overwrite
existing file.
• $ cat > test – Create test file (if not exist). If exist, overwrite the existing contents.
• $ cat >> test1 – Append the text followed by already existing contents.
• $ cat f1 f2 > file – create ‘file’, contain contents of f1 and followed by contents of f2.

September 22, 2009


Copy, Move and Remove Commands
• $ cp letter.a letter.b -> copy(Overwrite if exist) contents from letter.a to
letter.b.
• $ cp let.a let.b letters -> copy the mentioned files into directory ‘letters'.
• $ cp /usr/aa16/chapter1 /usr/aa16/newbook/chap1 -> files copied from
one directory to other.
• $ rm –I file -> removes file interactively (ask for user confirmation
before deleting)
• $ rm –r dir1 -> removes all contents inside directory dir1 and also
dir1.(-f option removes files forcibly)
• $ mv file1 file2 -> rename of file1 to file2.
• $ mv olddir newdir -> renam directory olddir to newdir (if not, create)
• $ mv file1 file2 newdir -> remove files file1, file2 from current location
and paste into directory ‘newdir’.

September 22, 2009


Listing of files
• $ ls Æ List all the files inside current directory
• $ ls –a Æ List including hidden files also.
• $ ls p* Æ list files start with letter ‘p'.
• Ex: $ ls ?ain, $ ls [aeiou]*, $ ls /mydir/*x
• $ lc Æ displays all files in columnwise
• $ lf Æ provides * for executable files, / with end of file for sub-directories.

September 22, 2009


Directory related commands
• $ pwd Æ Present Working Directory
• $ mkdir –p works/bpb/unix/book Æ create directories in single command
• $ mkdir –m 754 newdor Æ create newdir with pemission number 754
• $ rmdir Æ removong the specified directory
• $ cd Æ used to change directory

September 22, 2009


Touch – another view
• Touch - By touching a file you either create it if it did not exists (with 0 lengths).
• Or you update it’s last modification and access times.
• There are options –a, -e and -m to override the default behavior.
• $ touch file

September 22, 2009


More - Command
• - used to control input by pages - like the dos /p argument with dir. e.g.
• $ more /etc/motd
*******************************************************************************
•* *
•* *
• * Welcome to AIX Version 4.1!
• $ more /etc/motd
*******************************************************************************
•* *
•* *
• * Welcome to AIX Version 4.1! *
**
**
* Please see the README file in /usr/lpp/bos for information pertinent to *
• * this release of the AIX Operating System. *
•* *
•* *
• *******************************************************************************
September 22, 2009
• motd: END
•Useful keys for use with more:
•b (back a page)
•' (go to top)
•v (vi the file)
•/ (Search)
•q (quit)
•' ' (down a page)
•Control-G (View current line number
•<CR> (down a line)
•See also pg which is extremely similar

September 22, 2009


Pg - Command
•- used to control input by pages - like the dos /p argument.
pg performs the same function as the more command but
has different control, as it is based on ex
Helpful keys for pg: 1 (go to top)
•$ (go to bottom)
•h (help)
•/ (Search)
•? (Search back)
•q (quit)
•-1 (back a page)

September 22, 2009


File related commands
• wc- command used to display the count of lines,words and characters using options –l,-
w,-c respectively. Ex: $ wc –lc file1
• Sort – command used to sort, merge files.
$ sort –o result file1 file2 ->result will have the sorted contents of file1 and file2.
-u option for only unique lines
-m option for merging sorted files

September 22, 2009


Find & Split - Command
• Find - Looks up a file in a directory tree.
• $ find . –name ‘name’
• $ find . \ (-name ‘w*’ -or -name ‘W*’ \)
• split -<split> <Filename> - Splits a file into several files.
• e.g. $ split -5000 CALLS1 # will split file CALLS1 into smaller files of 5000 lines each
called xaa, xab, xac, etc

September 22, 2009


Cut and grep commands
• Cut – picks up a number of character or fields from the file.
• $ cut –f 2-7 empinfo -> empinfo contain fields from 2 to 7 from the file.
• Cut command assumes that fields are separated by tab chaacter. If any other character
used to separate, we can mention in the option –d.
• $ cut –f 2-7 –d”:” empinfo -> where the same files ae separated by “:”

September 22, 2009


Grep Command
• Grep ->Globally search a Regular Expression and Print it.
• $ grep picture file->search the word ‘picture’ in ‘file’, if found, lines containing that word
would be displayed.
• $ grep picture file1 file2 ->display the searched lines along with the filename.
• $ grep ‘the picture in’ –i –n newfile storyfile
• ->I option to ignore case sensitive (Insensitive)
• -> n option to display th number of lines also at the end for each file.

September 22, 2009


Grep Command

•$ grep [Rr]epel myfile -> display all occurences of Reel as


well as rebel and display the lines containing one of these.
•$ grep b??k myfile -> display all four letter words whose
first letter should be ‘b’ and last character should be ‘k'.
•$ grep –v a* myfile -> display lines that don not contain
words starting with ‘a'.
•-c option Æ display only number of matches
•-s option Æ suppresses error messages
•-v option Æ return lines that do not match the text.

September 22, 2009


Viewing files

•$ head -10 myfile -> displays first 10 lines from the file
•$ tail -15 my file -> displays the last 15 lines from the file.
•$ pg +10 -15 –p “Page No. %d:” -s myfile
•-> displaying the 15 lines at a time from 10th line and at the
end prompt comes which display the page number on
view.
•$ more +15 -10 –s –d myfile yourfile ->
•Only difference is displaying contents from two files and
also –s option will squeeze multiple blank lines in a file to
single blank line.

September 22, 2009


History Commands
•History - Display a history of recently used commands
•• $ history – all commands in the history
•• $ history 10 –> last 10
•• $ history -r 10 –> reverse order
•• $ !! –> repeat last command
•• $ !n –> repeat command n in the history
•• $ !-1 –> repeat last command = !!
•• $ !-2 –> repeat second last command
•• $ !ca –> repeat last command that begins with ‘ca’

September 22, 2009


Wild Cards
• Wild cards: Æ may be used in directory parts of pathname
• * Æ match zero or more characters. Ex: ASN*
• ? Æ match any single character. Ex: AN?
• […] Æ match any single character from bracketed set. Range of characters can be
specified with [ - ]
• [!...] Æ match any single character NOT in bracketed set.

September 22, 2009


• A shell is an environment in which we can run our commands,
programs, and shell scripts. There are different flavors of shells, just
as there are different flavors of operating systems. Each flavor of shell
has its own set of recognized commands and functions.
• Korn Shell /bin/ksh OR /usr/bin/ksh
•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.

September 22, 2009


• Shell scripts and functions are both interpreted. This means they are not compiled. Both
shell scripts and functions are ASCII text that is read by the Korn shell command
interpreter. When we execute a shell script, or function, a command interpreter goes
through the ASCII text line by line, loop by loop, test by test and executes each
statement, as each line is reached from the top to the bottom.

September 22, 2009


• A Function Has the Form
• function function_name { commands to execute } orfunction_name () {
commands to execute }When we write functions into our scripts we must remember to
declare, or write, the function before we use it: The function must appear above the
command statement calling the function.

September 22, 2009


When to use Script?

• Customizing your work environment. For Ex; every time you login if you want to see
current date, a welcome message and list of users who logged in, you can write shell
script.
• Automating your daily tasks. For Ex; Backing up all our programs at the end of day or
week.
• Executing some system procedures like shutting down the system, formatting a disk etc.
• Performing same operations on many files.

September 22, 2009


When should not use?

• When task is too complex, such as writing entire billing systems


• When task requires high degree of efficiency
• When task requires a variety of tools

September 22, 2009


Variables in UNIX
• There are two types of variables:

• UNIX-defined or System Variables:

•These are standard variables which are always


accessible. Shell provides the values for these variables.

• User-Defined Variables:

•These are defined by us and are used most extensively in


shell programming.

September 22, 2009


• There are special parameters that allow accessing all of the
command-line arguments at once. $* and $@ both will act the same
unless they are enclosed in double quotes, " ".
• Special Parameter Definitions
• The $* special parameter specifies all command-line arguments.
• The $@ special parameter also specifies all command-line arguments.
• The "$*" special parameter takes the entire list as one argument
with spaces between.
• The "$@" special parameter takes the entire list and separates it
into separate arguments.

September 22, 2009


• Declare the Shell in the Shell Script
• Declare the shell! If we want to have complete control over how a shell script
is going to run and in which shell it is to execute, we MUST declare the shell in
the very first line of the script. If no shell is declared, the script will execute in
the default shell, defined by the system for the user executing the shell script.
If the script was written, for example, to execute in Korn shell ksh, and the
default shell for the user executing the shell script is the C shell csh, then the
script will most likely have a failure during execution.
• Ex: #!/usr/bin/ksh OR #!/bin/ksh.

September 22, 2009


• #!/usr/bin/ksh## SCRIPT: NAME_of_SCRIPT
• # AUTHOR: AUTHORS_NAME
• # DATE: DATE_of_CREATION
• # REV: 1.1.A (Valid are A, B, D, T and P)# (For Alpha, Beta, Dev, Test and
Production)#
• # PLATFORM: (SPECIFY: AIX, HP-UX, Linux, Solaris # or Not platform
dependent)#
• # PURPOSE: Give a clear, and if necessary, long, description of the# purpose of the shell
script. #####################################################################
DEFINE FILES AND VARIABLES HERE
######################################################################## DEFINE
FUNCTIONS HERE ############################################################
############## BEGINNING OF MAIN
################################################################################
##
• End of script

September 22, 2009


• The following control structures will be used extensively.
• if ... then Statement
• if [ test_command ]
• then commands fi
• if ... then ... else Statement
• if [ test_command ]
• then commands
• else commands fi
• if ... then ... elif ... (else) Statement
• if [ test_command ]
• then commands
• elif [ test_command ]
• then commands. .
• else (Optional) commands
• fi

September 22, 2009


• for ... in Statement
• for loop_variable in argument_list
do
commands
done
while Statement
• while test_command_is_true
do
commands
done
until Statement

September 22, 2009


• until test_command_is_true
do
commands
done
case Statement
• case $variable in
• match_1)
commands_to_execute_for_1
;;
• Match_2)
commands_to_execute_for_1
;;
.
.
*) (Optional) commands_to_execute_for_no_match ;;
Esac

September 22, 2009


• Using break, continue, exit, and return
• It is sometimes necessary to break out of a for or while loop, continue in the
next block of code, exit completely out of the script, or return a function's
result back to the script that called the function.
• break is used to terminate the execution of the entire loop, after completing
the execution of all of the lines of code up to the break statement. It then
steps down to the code following the end of the loop.
• continue is used to transfer control to the next set of code, but it continues
execution of the loop.
• exit will do just what one would expect: It exits the entire script. An integer
may be added to an exit command (for example, exit 0), which will be sent as
the return code.
• return is used in a function to send data back, or return a result, to the calling
script.

September 22, 2009


•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. This is why it is called a here document: The required
input is here, as opposed to somewhere else.
•Syntax for a Here Document
•program_name
<<LABELProgram_Input_1Program_Input_2Program_Input_3
Program_Input_# LABEL Example:
•/usr/local/bin/My_program << EOFRandyRobinRustyJimEOF

September 22, 2009


•We can set the attribute to always translate all of the
characters to uppercase or lowercase. To set the case
attribute of VARIABLE to always translate characters to
uppercase we use:
• Example:
• typeset -u VARIABLE
• VARIABLE="True"
echo $VARIABLE
TRUE
The available options are –u, -l

September 22, 2009


• Whenever we run a command there is a response back from the system about the last
command that was executed, known as the return code. If the command was
successful the return code will be 0, zero. If it was not successful the return will be
something other than 0, zero. To check the return code we look at the value of the $?
shell variable.
• As an example, we want to check if the /usr/local/bin directory exists. Each of these
blocks of code accomplishes the exact same thing:
• test -d /usr/local/binif [ "$?" -eq 0 ] # Check the return codethen # The return
code is zero echo '/usr/local/bin does exist' else # The return code is NOT
zero echo '/usr/local/bin does NOT exist' fi

September 22, 2009


• PS3="Is today your birthday? "
• echo "\n"
• select menu_selections in Yes No Quit
• docase $menu_selections in
• Yes) echo "\nHappy Birthday!\n"
• ;;
• No) print "\nIt is someone's birthday today...\Sorry it is not yours\n"
• ;;
• Quit) print "\nLater tater!\n"
• break
• ;;
• *) print "\nInvalid Answer...Please try again\n"
• ;;
• Esac
• done

September 22, 2009


Conclusion
• This training material will be used as an reference for learning basics about
unix's commands.
To know more about Unix Commands Refer:
– UNIX: The Complete Reference

by Kenneth H Rosen, Douglas A Host, Rachel Klee,

September 22, 2009

Vous aimerez peut-être aussi