unix basic commands

41
September 22, 2009 TCS Public UNIX Basic Commands Author: Anand P Creation date: 23-08-2009 Version: 0.1 Training Level: E0

Upload: pavan-kumar

Post on 28-Nov-2014

185 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: UNIX Basic Commands

September 22, 2009 TCS Public

UNIXBasic Commands

Author: Anand P

Creation date: 23-08-2009

Version: 0.1

Training Level: E0

Page 2: UNIX Basic Commands

September 22, 2009

Page 3: UNIX Basic Commands

September 22, 2009

Table of ContentsIntroductionBasic CommandsAlias & Unalias CommandsDirectory Related commandsFile Related CommandsDefinition of ShellShell Script Vs FunctionsFunctionsVariables in UnixControl StructuresConclusion

Page 4: UNIX Basic Commands

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 usefulUnix Commands, including examples of how to use each command.

Page 5: UNIX Basic Commands

September 22, 2009

• $ 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

WHO & WHO AM I

Page 6: UNIX Basic Commands

September 22, 2009

• 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

Basic Procedure

Page 7: UNIX Basic Commands

September 22, 2009

•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

Alias & Unalias Commands

Page 8: UNIX Basic Commands

September 22, 2009

• 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.

Creation of files

Page 9: UNIX Basic Commands

September 22, 2009

• $ 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’.

Copy, Move and Remove Commands

Page 10: UNIX Basic Commands

September 22, 2009

• $ 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.

Listing of files

Page 11: UNIX Basic Commands

September 22, 2009

• $ 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

Directory related commands

Page 12: UNIX Basic Commands

September 22, 2009

• 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

Touch –

another view

Page 13: UNIX Basic Commands

September 22, 2009

• - 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. * • * * • * * • ******************************************************************************* • motd: END

More -

Command

Page 14: UNIX Basic Commands

September 22, 2009

•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

Page 15: UNIX Basic Commands

September 22, 2009

•- 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)

Pg -

Command

Page 16: UNIX Basic Commands

September 22, 2009

• 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

File related commands

Page 17: UNIX Basic Commands

September 22, 2009

• 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

Find & Split -

Command

Page 18: UNIX Basic Commands

September 22, 2009

• 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 “:”

Cut and grep commands

Page 19: UNIX Basic Commands

September 22, 2009

• 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.

Grep Command

Page 20: UNIX Basic Commands

September 22, 2009

•$ 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.

Grep Command

Page 21: UNIX Basic Commands

September 22, 2009

•$ 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.

Viewing files

Page 22: UNIX Basic Commands

September 22, 2009

•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’

History Commands

Page 23: UNIX Basic Commands

September 22, 2009

• 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.

Wild Cards

Page 24: UNIX Basic Commands

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.

Page 25: UNIX Basic Commands

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.

Page 26: UNIX Basic Commands

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.

Page 27: UNIX Basic Commands

September 22, 2009

• 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.

When to use Script?

Page 28: UNIX Basic Commands

September 22, 2009

• 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

When should not use?

Page 29: UNIX Basic Commands

September 22, 2009

• 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.

Variables in UNIX

Page 30: UNIX Basic Commands

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.

Page 31: UNIX Basic Commands

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.

Page 32: UNIX Basic Commands

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

Page 33: UNIX Basic Commands

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

Page 34: UNIX Basic Commands

September 22, 2009

• for ... in Statement• for loop_variable in argument_list

docommands

done while Statement• while test_command_is_true

docommands

doneuntil Statement

Page 35: UNIX Basic Commands

September 22, 2009

• until test_command_is_truedo

commandsdone

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

Page 36: UNIX Basic Commands

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.

Page 37: UNIX Basic Commands

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

Page 38: UNIX Basic Commands

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 $VARIABLETRUE

The available options are –u, -l

Page 39: UNIX Basic Commands

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

Page 40: UNIX Basic Commands

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

Page 41: UNIX Basic Commands

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,