Você está na página 1de 32

E4`1jrc1qsasp01 /home/sukumar/arun:alias rm='rm -f' vi command \<part : search for word : part.

Thus partner would qualify whreas depart would not. :part\> will search for all the strings whichend with the word part.Thus depart would qualify whreas partner would not. /\<part\> Search only the word part While searching a pattern you may want to ignore case. (ESC:set ignorecase or (ESC :set ic

File/Directory Manipulation
compress files Reduces the size of a file. uncompress files Restores compressed files to their original form. cp file1 file2 Copy file(s). cp files directory Copy file(s) into a directory. cp -r dir1 dir2 Copy a directory and, recursively, its subdirectories. mkdir directory Create, or "make" a directory. mv file1 file2 Move a file or, if file1 and file2 are in the same directory, rename a file. mv files directory Move files into a directory. mv dir1 dir2 If directory dir2 exists, move dir1 into dir2; otherwise, rename dir1 as dir2. rm files Remove (erase) file(s). rm i : Removes interactively rm rf : Removes recursively and forcefully rm -r names Remove files, directories, and recursively, any subdirectories.

rmdir directory Remove directory (directory must be empty).

HOME directory : The directory you go when you log in.


Cd $HOME

File System Navigation


cd Return to your home directory. cd directory Change directory to make directory your current directory. file files Determine file type. ls List the contents of the current directory. ls names List the contents of the directories; names can name files and/or directories: ls -l . . . in a long format, showing permissions, owner, size, and other file info. ls -a . . . all files, including "hidden" files (file names that begin with a dot "."). ls -R . . . Recursively, for all subdirectories. ls -t . . . in time order (when modified, newest to oldest) rather than in name order. pwd Display the name of the current directory, or "print working directory."
.filename is hidden files , can be see with ls -a

Data Manipulation
cat files Concatenate file(s); you can use cat to display the contents of a file (this is not advisable if the file is a binary file). grep "pattern" files Display all lines in the files that match a pattern. more files Display contents of files one screen at a time. sort files Order the lines in a file or files alphabetically (this command does not alter the file or files -- it merely displays the sorted output to the screen): sort -r files . . . in reverse order. sort -n files . . . numerically (puts 2 before 10 instead of after).

jrc1qsasp01 /home/sukumar/arun:sort bbb 10 2 jrc1qsasp01 /home/sukumar/arun:sort -n bbb 2 10 jrc1qsasp01 /home/sukumar/arun: Directories How to make a new directory ? Answer = mkdir <dir name> for eg lyca /home/sukumar/arun:mkdir out lyca /home/sukumar/arun:ls -ltr |grep ^d drwxr-xr-x 2 sukumar operatio 512 Sep 3 14:36 out/ How to change the directory

Answer = cd dirname for eg

lyca /home/sukumar/arun:cd out lyca /home/sukumar/arun/out What does pwd command will do ?

Full form is Present working directory , Tells you where you currently are. for eg:
lyca /home/sukumar/arun/out:pwd /home/sukumar/arun/out

How to remove directory ? rmdir <directory_name> for eg lyca /home/sukumar/arun:rmdir out lyca /home/sukumar/arun: Note : Make sure all files are deleted from current directory before rmdir How to capture the entire text of ps command /usr/ucb/ps wwaxu 17772

Mkdir p :: allows you to create multiple generations of directories , at one go $mkdir p works/bpb/Unix/book -p option tells unix to first create works then within it bpb next child directory unix and lastly book. 2) mkdir m : suppose you want to create a directory which should have permission 754,irrespective of the unmask value Eg :: $mkdir m 754 newdir

Basic Commands How to display home directory on screen ? $HOME Copy files from one directory to other Copy directory recursively? cp R

copy a directory, recursive .. and preserve file dates cp -Rp /app/datafiles /aux/backup2006
Copy file from one directory to other with different name cp suraj arun Rename directory newdir as olddir Answer:: mv newdir olddir How to remove a directory containing files and subdirectories Answer:: rm rf olddir How to delete file interactively ? Answer:: rm i <file name> Rename file gold-words under the directory olddir as golden-words and verify that the file has been renamed. Answer:: cp gold-words ./olddir/golden-words List out all files end with .c Answer:: ls lrt *.c Move all the files end with .c to olddir Answer:: mv /home/sukumar/arun/*.c /home/sukumar/arun/olddir/ Create 3 empty files empty1, empty2 and empty3 Answer:: touch empty1 empty2 empty3 Change the permission of file newtext to 664 Amswer:: chmod 664 newtext 4 read ,2 write ,1 execute What will the following commands will do ? Question :: ls a? , ls a* , ls *.* , ls [!abc]art, ls [a!bc]art, ls [b-dku-z]* jrc1qsasp01 /home/sukumar/arun:ls -lrt [!b] -rw-r--r-- 1 sukumar operations 235 Sep 8 11:56 -rw-r--r-- 1 sukumar operations 326 Sep 17 21:46 c -rw-r--r-- 1 sukumar operations 0 Sep 23 10:11 1 -rwxrwxrwx 1 sukumar operations 22 Oct 10 06:49 a Delete directories mydir and newdir and their contents at one shot Answer:: rm rf mydir newdir

Suppose the path dir1/dir2/dir3/dir4 exists in your directory. All these directory are empty. How would you remove all of them in one shot.

Permissions

There are three types of permissions (what allowed to do with a file):


read access write access execute access

Permissions are defined for three types of users:


the owner of the file the group that the owner belongs to other users

For Eg: Look at the first portion of ls -lrt lyca /home/sukumar/arun:ls -lrt notes -rw-r--r-- 1 sukumar operatio 364 Sep 3 07:48 notes -rw-r--r-012345678

Symbol in the position 0 ("-")is the type of the file. It is either "d" if the item is a directory, or "l" if it is a link, or "-" if the item is a regular file. Symbols in positions 1 to 3 ("rwx") are permissions for the owner of the file. Symbols in positions 4 to 6 ("r--") are permissions for the group. Symbols in positions 7 to 9 ("r--") are permissions for others.

2.1.1. Examples File, owner has read, write, execute permissions, -rwxr-xr-x group: only read and execute permissions, others: only read and execute permissions. Directory, dr-x------ owner has read and execute access, group and others have no access
Give following commands:

lyca /home/sukumar/arun:ls -lrt notes -rw-r--r-- 1 sukumar operatio 364 Sep 3 07:48 notes lyca /home/sukumar/arun:chmod 744 notes lyca /home/sukumar/arun:ls -lrt notes -rwxr--r-- 1 sukumar operatio 364 Sep 3 07:48 notes*

"1" stands for execute only, "2" stands for write only, "4" stands for read only. To combine the permissions you can simply add 1, 2 and 4 to get a needed combination. For instance, to get read and write permissions, you add 4 (read) and 2 (write), thus getting 6 (read and write). To get read and execute permissions, you add 4 (read) and 1 (execute), thus getting 5 (read and execute).: 2.2.1. Examples owner: read and write permissions, 644 group: only read permissions, others: only read permissions. owner: read, write and execute permissions, 755 group: read and execute permissions, others: read and execute permissions.

Difference in access permissions for files and folders


Access type Read Write Execute File If the file contents can be read If user or process can write to the file (change its contents) If the file can be executed Folder If the directory listing can be obtained If user or process can change directory contents somehow: create new or delete existing files in the directory or rename files. If user or process can access the directory, that is, go to it (make it to be the current working directory)

grep
Search Pattern Grep search patterns

Align the match from the end of the line. Eg: grep New[abc]$

Align the match from the beginning of the line. Eg: grep ^New[abc]

^within [ ] :Pattern must not contain any character in the set specified. Eg : grep New[^abc] ? + * . [] Match one or less sequential repetitions of the pattern. Match one or more sequential repetitions of the pattern. Match zero or more sequential repetitions of the pattern. Match any single character. Eg : grep New.[abc] Match any single character or range of characters enclosed in the brackets.

grep '^.Pp' myfile

Some common option: -v - invert (print all lines except those that contain the pattern). -i - ignore case of letters (small and capital treated as the same) -l - (list) - print a list of the file names where mathes found -s - suppress error messages about nonexistent or unreadable files. -c - print only a count of the lines that contain the pattern. -n - precede each line by its line number in the file (first line is 1). Ranges: [0-3] is the same as [0123] [a-k] is the same as [abcdefghijk] [A-C] is the same as [ABC] [A-Ca-k] is the same as [ABCabcdefghijk]

1.6.2 Filenames and Wildcards


Expression Matches [abc] a, b, or c [.,;] Period, comma, or semicolon [-_] Dash and underscore [a-c] a, b, or c [a-z] All lowercase letters [!0-9] All non-digits [0-9!] All digits and exclamation point [a-zA-Z] All lower- and uppercase letters [a-zA-Z0-9_-] All letters, all digits, underscore, and dash

Searches word suraj in all files in current directory Answer = grep suraj * Search word arun in all files whose extension is out ( for eg: order.out,sales.out) Answer = grep arun *.out List the directories in /home/sukumar path ( No files ) Answer = cd /home/sukumar ls -lrt | grep ^d Examples::

grep 'hello\.gif' file - matches hello.gif grep 'hello.gif' file - matches lines containing hello-gif , hello1gif , helloagif , etc.

Cat :

used to display files

touch
touch is a standard Unix program used to change a files access and modification timestamps. It is also used to create a new empty file. Eg
touch myfile.txt

Here's how to change the date and time of a file. # touch -t yyyymmddhhmi.ss filename touch -t 199810311530.00 hallowfile # touch -t 200701310846.26 index.html
# touch -d '2007-01-31 8:46:26' index.html # touch -d 'Jan 31 2007 8:46:26' index.html

wc
wc - print the number of newlines, words, and bytes in files -c, --bytes print the byte counts -m, --chars

print the character counts -l, --lines print the newline counts -L, --max-line-length print the length of the longest line -w, --words print the word counts.

compress
"compress" command is used to compress files. Notes: The compressed file replaces the original file, and a new filename is created by adding a ".Z" extension to the original filename. Examples: compress /tmp/myfiles.tar This command compresses the file /tmp/myfiles.tar, and replaces it with a file named /tmp/myfiles.tar.Z. lyca /home/sukumar/arun:compress -v foo.tar foo.tar: Compression: 80.11% -- replaced with foo.tar.Z

more is a command to view (but not modify) the contents of a text file one screen at a time more <file name>

more

tar

This command is used to create new archives, list files in existing archives, and extract files from archives(record, files) `. The tar program takes one of three funcion command line arguments.

c --- to create a tar file, writing the file starts at the beginning. t --- table of contents, see the names of all files or those specified in other command line arguments. x --- extract (restore) the contents of the tar file. v --- verbose output, show, e.g., during create or extract, the files being stored into or restored from the tar file. f --- specifies the filename (which follows the f) used to tar into or to tar out from; see the examples below.

Examples tar cvf /tmp/home.tar /home


This command creates a tar archive named /tmp/home.tar. The tar command copies the files in the /home directory, and all subdirectories of /home.

tar cvf /tmp/home.tar /home compress /tmp/home.tar


This example shows two commands issued in sequence. The first command creates a tar archive named /tmp/home.tar. The second command compresses the tar archive, and replaces it with a new compressed tar archive, named /tmp/home.tar.Z.

To tar all .out and into a tar file named foo.tar use:
tar -cvf foo.tar *.out

To see a tar file's table of contents use:


tar -tvf foo.tar

To extract the contents of a tar file use:


tar -xvf foo.tar

You can extract only one (or several) files if you know the name of the file. For example, to extract the file named anagram.cc from the tarfile foo.tar:
tar -xvzf foo.tar anagram.cc tar subdirectories for specific files ( for eg: only *.csv want to tar) find . -name *.csv|xargs tar cvf tarfilename.tar

# append files to a tar file tar rvfn myfile.tar *.txt

tail

tail is a program on Unix used to display the last few lines of a text file or piped data. : tail -20 file1 (display last 20 lines of a file)

tail -f /var/adm/message This is particularly useful for monitoring log files. As new lines are added to the file by another process, tail updates the display

head
The external head command displays the first few lines of a file. Examples: head -25 file1 head -1000 file2 > output

date
# date formatting, yields 112098 for example date '+%m%d%y' -- Date formatting archive_id=`date +'%Y%m%d'`

pg
This filter is used to display a large file, a screenfile at a time. Example: pg file1 cat file1 | pg

uname command
prints the name, version and other details about the current machine and the operating system running on it. Eg: Uname a ### prints basic info Uname X ### Print detailed information
lyca /home/sukumar/arun:uname -X System = SunOS Node = lyca Release = 5.9 KernelID = Generic_117171-07 Machine = sun4u BusType = <unknown> Serial = <unknown> Users = <unknown> OEM# = 0

Origin# = 1 NumCPU = 1 lyca /home/sukumar/arun:uname -a SunOS lyca 5.9 Generic_117171-07 sun4u sparc SUNW,UltraAX-i2

id
id - print UIDs and GIDs (user id and group id) for eg: lyca /home/sukumar/arun:id uid=29893(sukumar) gid=10004(operations)

sleep
sleep is a Unix command line program that suspends program execution for a specified period of time. The sleep instruction suspends the calling process for at least the specified number of second , minutes, hours or days.
s m h d (seconds) (minutes) (hours) (days)

Examples
sleep 5 : Causes the current terminal session to wait 5 seconds. The default unit is seconds.

sleep 10 - sleeps for 10 seconds


sleep 5h

Causes the current terminal session to wait 5 hours

Input output redirection and piping


Input redirection : cat < test1 or cat 0<test (here 0 indicates input redirection) Output redirection : cat test1 > test2 or cat test 1> testnew ( here 1 indicates output redirection ) or cat test1 >> test2 Error redirection : cat test 2> error-mesg ( here 2 indicates error redirection ) Examples:

command1 > file1 executes command1, placing the output in file1 command1 < file1 file1 as the source of input (as opposed to the keyboard) command1 < infile > outfile combines the two capabilities: command1 reads

from infile and writes to outfile

What will be the effect of following commands:

1. 2. 3. 4. 5. 6. 7. 8. 9.

cat < file1 > file2 wc l < aaa who | sort who | wc l > aaa date > aaa ls | grep suraj grep poem file | sort | wc l ls | tee file1 | grep poem | wc l cat aaa > bbb 2> ccc

What is the difference between the commands: Cat <file1>file2 Cat > file2 < file1 who > ccc | grep Mar ccc | sort | wc -l Merge the contents of the files a.txt, b.txt and c.txt and store it in a file my_output.out Answer:: cat a.txt b.txt c.txt > my_ output.out What will the output of following commands: Cat > f1 <f2 Cat f2 > f1 Cat < f2 > f1

$cat myfile > newfile 2> errorfile if newfile doesnt exist , error message instead of displaying on screen it will be redirected to errorfile.

Command substitution
The shell reads the command, or list of commands, or pipeline from between the grave accents and executes them. The output
Grave accent `` is used for this.

from this operation is then available to the shell for use in setting a variable or echoing to the terminal

Example grave accent


currentDir=`pwd` lineCount=`wc -l $fileName | cut -c1-8` thirdPath=`echo $PATH | cut -f3-3 -d:`

expr
The shell does not support numeric variables. All variables are treated as character strings . The expr command is used to evaluate arithmetic expressions. For eg : $expr 4 +5 will display 9 on the screen. var1=123 var2=2000 echo `expr $var1 + $var2` Note: expr does not support decimals $expr 5/2 will display 2 and NOT 2.5 Examples Var1=`expr $var + 20 A=`expr $var1 7` B=`expr $a \* $b`

ftp command
The FTP (File Transfer Protocol) utility program is commonly used for copying files to and from other computers ftp <machine name>

Different options of FTP


ftp> get <file name> ## Retrieve single file from remote machine ## ftp > ascii ## Set the file transfer type to ASCII ftp> mget *.out ## Retrieve multiple file from remote machine ## ftp> put abc.out ## Put or copy single file to remote machine ## ftp> mput ab*.ksh ## Put or copy multiple files to remote machine ## ftp> prompt off ## switch off Interactive mode ## ftp> hash ## to To monitor the progress of a transfer ## ftp> binary ## To get binary files ##

mget

to copy multiple files from the remote machine to the local machine; you are prompted for a y/n answer before transferring each file

How to automate the ftp in shell script?


AUTOMATIC FTP ------------ftp -n 132.180.8.18 <<! user dba passwordOfdba prompt off binary cd /wiprodba cd dba mget *sh* bye ! OR

SCP command Securely copies the file across the network.


Destination server Scp -rp sukumar@sea1qsasp06:/sources path/file name <destination path> -p : same permission as of source db file

tee command
tee is normally used to split the output of a program so that it can be seen on the display and also be saved in a file. -a option will append the output Eg: ls | tee ls.txt sort somefile.txt | tee sorted_file.txt | uniq -c | head 12 > top12.txt jrc1qsasp01 /home/sukumar/arun:uname | tee -a aaa SunOS jrc1qsasp01 /home/sukumar/arun:cat aaa What is the difference between
script_file > log_file script_file | tee log_file

nohup command
All processes are killed when you log out. If you want a background process to continue running after you log out, you must use the nohup command to submit that background command Examples:
nohup grep word * > word.list & $ nohup abcd & $ exit Nohup bcp master..syslogins out /home/sukumar/arun/syslogins -c -Usa -Sqa1client948 -Phello123 & Below example shows how to redirect output to a file other than nohup.out. $ nohup abcd > out.file &

egrep command
The egrep command searches the lines of the specified files (or of standard input) for occurrences of pattern. Egrep pattern1|pattern2|pattern3 <file name> $ egrep ' paper | people ' fortunes $ egrep i Password fortunes ## Ignore case sensitive ## Absence sort

uniq
To remove consecutive duplicate lines from a file:
uniq acc_nos accounts

This removes all consecutive duplicate lines from the file acc_nos and places the output in the file accounts.

Cut

The cut filter of UNIX is useful when specific columns from the output of certain commands ( like ls,who ) need to be extracted. The external cut command displays selected columns or fields from each line of a file. The default delimiter is TAB cut -c 1-5 a.dat cut -d ' ' -f 2-7 cut -c 4,5,20 foo cut -c 1-5 a.dat cut -d ":" -f1,7 /etc/passwd cut -d ":" -f 1,

6- /etc/passwd # cuts fields 1,6 to the end of line.

cut -d":" -f-6 /etc/passwd | grep vbabu echo "suraj" |cut -c-2 jrc1qsasp01 /home/sukumar/arun:echo suraj | cut -c -2 su

EXIT
It cause the shell to exit

TR COMMAND
---------a. Squezzing the blank space where deliminator is blank space tr -s " " " " ( multiple space to single space ) b. converting the deliminator tr -s " " ":" (Converting deliminator from space to ':' c. Squezzing the blank space where deliminator is ':' tr -s ":" ":" jrc1qsasp01 /home/sukumar/arun:cat /etc/passwd | grep vbabu vbabu:x:29761:10004:Ventkat Babu:/export/home/vbabu:/bin/ksh cat /etc/passwd | tr -s ":" " " |grep vbabu vbabu x 29761 10004 Ventkat Babu /export/home/vbabu /bin/ksh jrc1qsasp01 /home/sukumar/arun:c

Find the size of directories Command : du sea1qsasp05:/d2/sybback/tmpdumps/qa1client943/dumps $ du -sk * 42456 auditdb_11-11-07_20:15:26.dmp

134224 client_11-11-07_20:15:26.dmp 358808 common_11-11-07_20:15:26.dmp Sort sizewise in descending order sea1qsasp05:/d2/sybback/tmpdumps/qa1client943/dumps $ du -sk * | sort -nr 4574508 newdumps 1029840 tic_gen_11-11-07_20:15:26.dmp 358808 common_11-11-07_20:15:26.dmp 134224 client_11-11-07_20:15:26.dmp 42456 auditdb_11-11-07_20:15:26.dmp Sort sizewise NOT in ascending order in human readable format SORTING IN HUMAN READABLE FORMAT du -sk * | sort -n -| cut -f2 | xargs du sh find ./ -name "*" -exec du -sk {} \; | sort -n |cut -f2|xargs du sh jrc1qsasp01 /home/sukumar/arun:find

/home/sukumar/arun -name

"*.out" -print | xargs ls -lrt


-rw-r--r-- 1 sukumar operations 13 Oct 15 12:12 /home/sukumar/arun/ab1.out -rw-r--r-- 1 sukumar operations 7 Oct 15 12:13 /home/sukumar/arun/ab2.out -rw-r--r-- 1 sukumar operations 7 Oct 15 12:15 /home/sukumar/arun/ab3.out -rw-r--r-- 1 sukumar operations 13 Oct 15 12:16 /home/sukumar/arun/ab4.out -rw-r--r-- 1 sukumar operations 11 Oct 15 15:44 /home/sukumar/arun/sonal123.out -rw-r--r-- 1 sukumar operations 7 Oct 15 15:53 /home/sukumar/arun/sonalN.out -rw-r--r-- 1 sukumar operations 11 Oct 15 15:55 /home/sukumar/arun/sonalplain.out -rw-r--r-- 1 sukumar operations 957 Nov 9 20:32 /home/sukumar/arun/qa1client100.out -rw-r--r-- 1 sukumar operations 462 Nov 9 20:32 /home/sukumar/arun/qa1client948.out -rw------- 1 sukumar operations 7 Mar 1 12:24 /home/sukumar/arun/file3.out -rw------- 1 sukumar operations 19 Mar 1 12:24 /home/sukumar/arun/file2.out -rw------- 1 sukumar operations 4 Mar 1 12:24 /home/sukumar/arun/file1.out -rw------- 1 sukumar operations 95 Mar 2 22:43 /home/sukumar/arun/nohup.out jrc1qsasp01 /home/sukumar/arun: sea1qsasp05:/d2/sybback/tmpdumps/qa1client943/dumps $ ; | sort -n |cut -f2|xargs du -sh < 616K ./newdumps/acc_fund24_Single_user.DMP 792K ./newdumps/acc_fund31_Single_user.DMP 1.1M ./newdumps/risk_Single_user.DMP

11M ./newdumps/trim_gen_Single_user.DMP 13M ./trim_gen_11-11-07_20:15:26.dmp 39M ./newdumps/auditdb_Single_user.DMP 41M ./auditdb_11-11-07_20:15:26.dmp 131M ./client_11-11-07_20:15:26.dmp 136M ./newdumps/client_Single_user.DMP 342M ./newdumps/common_Single_user.DMP 350M ./common_11-11-07_20:15:26.dmp 1006M ./tic_gen_11-11-07_20:15:26.dmp 1.0G ./newdumps/tic_gen_Single_user.DMP 2.8G ./newdumps/trim_client2_Single_user.DMP 4.4G ./newdumps 5.9G . sea1qsasp05:/d2/sybback/tmpdumps/qa1client943/dumps $ du -sk * | sort -n | cut -f2 | xargs du -sh 13M trim_gen_11-11-07_20:15:26.dmp 41M auditdb_11-11-07_20:15:26.dmp 131M client_11-11-07_20:15:26.dmp 350M common_11-11-07_20:15:26.dmp 1006M tic_gen_11-11-07_20:15:26.dmp 4.4G newdumps

Find command: find find find find find . -name "rc.conf" print . -name '[a-zA-Z]*.o' print . -name '*.o' -print ./ -type d -name ".svn" -print | xargs rm rf . -name "rc.conf" -exec chmod o+r '{}' \;

% find . -mtime -7 -name "*.c" print # find just those files that have been modified in the last seven days.

find . -mtime 7 -name "*.c" print # those files that were modified exactly seven days ago: % find . -mtime +30 -name "*.c" print # To find those C source files that I haven't touched for at least 30 days % find . -type d print # To find a list of the directories % find . -type d -exec ls -ld {} \; % find . -type f -exec grep -i mapping {} \; # grep i ignores uppercase

% find . -type f -exec grep -l -i mapping {} \; # grep l prints only file name matching pattern % find . -type f -print | xargs grep -l -i mapping find ./ \( -name core -o -name "*.out" \) print find ./ \(-name core o name *.out \) atime 7 exec rm {} \; ## command removes all the files named core and the files ending with in.out that have not been accessed in last seven days. find /home/sukumar/arun -not \( -name "*.sql" -o -name "*.out" \) -print ### All files except *.sql and *.out find /usr ! -newer /FirstFile -print ## To negate a test, put a ! before the option. find /usr ! -newer /FirstFile print find * -type f -print -o -type d prune ## lists all files in a directory but does not look at any files in subdirectories under the top level FINDING THE FILES WITH NOT CONDITION ---------------------------------------FIND . ! \( -name "seg*" -o -name "ftp*" \) -print control-z ?Stop (don't kill) the foreground job, and then return to the shell jobs ?Check the status of jobs in the current session rc1qsasp01 /home/sukumar/arun:jobs -l [2] + 14236 Stopped (SIGTSTP) ic qa1client948 [1] - 13018 Stopped (SIGTSTP) ic qa1client948 ps -u username ?Check the status of processes, including those from other sessions. kill -9 %1 ?Kill a job, by specifying its job number after the percent sign. kill -9 123 ?Kill a process, by specifying its process id (PID) number bg ?Run the most recently stopped job in the background fg ?Bring most recently backgrounded job to the foreground fg %1 ?Bring a job to foreground by specifying its job number after the percent sign Examples ## put bkjob in background lyca /home/sukumar/arun:bkjob & [1] 21244

Background jobs

# put secondjob in background lyca /home/sukumar/arun:secondjob & [2] 21270 # put thirdjob in background lyca /home/sukumar/arun:thirdjob & [3] 21282 ## See the status of all jobs running in background ## 1,2,3 is job id and 21282, 21270 and 21244 is unix process ID lyca /home/sukumar/arun:jobs -l [3] + 21282 Running thirdjob & [2] - 21270 Running secondjob & [1] 21244 Running bkjob & # put bkjob in foreground ## error comes because we need to specify Job id or unix process ID lyca /home/sukumar/arun:fg bkjob ksh: bkjob: Arguments must be %job or process ids # put bkjob in foreground ..NOW IT WORKED #Once the job is in foreground, press CTRL+z to stop the job lyca /home/sukumar/arun:fg %1 bkjob ^Z[1] + Stopped (SIGTSTP) bkjob & # Now the status is showing Stopped, other two processes are still running. lyca /home/sukumar/arun:jobs [1] + Stopped (SIGTSTP) bkjob & [3] - Running thirdjob & [2] Running secondjob & # Again resume the jobbkjob in background. lyca /home/sukumar/arun:bg %1 [1] bkjob & # Job bkjobis resumed again in background lyca /home/sukumar/arun:jobs [1] + Running bkjob & [3] - Running thirdjob & [2] Running secondjob & # Kill job id 1 ( kill bkjob) lyca /home/sukumar/arun:kill %1 [1] + Terminated bkjob & ## See the status of all jobs , first job is killed only two left

lyca /home/sukumar/arun:jobs [3] + Running thirdjob & [2] - Running secondjob & # Kill job id 2( kill secondjob) lyca /home/sukumar/arun:kill %2 [2] - Terminated secondjob & ## See the status remaining jobs, second job is also killed only one left. lyca /home/sukumar/arun:jobs -l [3] + 21282 Running thirdjob & # You can also kill jobs by reffering unix process ID. lyca /home/sukumar/arun:kill -9 21282 lyca /home/sukumar/arun:jobs -l [3] + 21282 Killed thirdjob & lyca /home/sukumar/arun:jobs -l lyca /home/sukumar/arun:

Mixed Examples

cat file.sql | sed -e "1,2d" > output.out echo suraj and arun > output.out echo suraj and arun >> output.out ls -al | tee poop.out cat access.log|grep 'msn'| tee msn_access.log|egrep '(jpg|png|gif)>out chmod 744 <file name> ,chmod 644 <file name>
find . -type l -print | xargs ls -ld | awk '{print $10}' ps -ef | grep -v ^oracle | grep -v ^root | grep -v ^nobody ps -ef | grep httpd | wc find . -mtime -7 -name 'j*html' -print - find files modified no more than 7 days # route output to both test.txt and std output ./runbackup | tee test.txt # sleep for 5 seconds sleep 5 find . -name *.csv|xargs tar cvf tarfilename.tar How to enable command line editing ? Soln : set o vi Search for $ in vi editor Soln : /\$

( cd - ) which changes to whatever directory you were in before the current one. For example, if you start out in /usr/lib, type cd without an argument to go to your home directory, and then type cd -, you will be back in /usr/lib.
# run a script, allow it to continue after logging off nohup runbackup &

# Here nohup.out will still be created, but any output will up in test70.log. Errors will appear in nohup.out. nohup /export/spare/hmc/scripts/test70 > test70.log & # Here nohup.out will not be created; any output will # show up in test70.log. Errors will appear test70.log also ! nohup /export/spare/hmc/scripts/test70 > test70.log 2>&1 &

show

FINDING THE SERVER LAST REBOOTED who -b Uptime How to search exact word test in directory. Soln : :grep "\<test\>" *

SHELL SCRIPTING
INPUT PARAMETERS DEFINATION IN SCRIPT -----------------------------$0 ----> First line on the command line (name of the script) $1 ----> First Input parameter $2 ----> Second Input parameter. $# ----> Number of Input parameters for a script. $* ----> Contains the entire string of input parameter .

$? - Reports the exit status of the last command.

EG: ksh check a b c $0 --> check $1 --> a $2 --> b Eg

Difference $* and $@ Usage:ss55 file1 file2 file3 Cat $* Cat $@ Sol The two command would become Cat f1 f2 f3 Cat f1 f2 f3 On execution , the first command give error since there is no file file1 file2 file3. Second command will displays the content of file file1,file2 and file3. When not enclosed within behave exactly the same.

Different Loops in Unix while read a do echo $a echo "TEST" done < File_Name cat dblist |while true read a do echo "use $a" >>updstat.sql done
a="0" while [ $a -lt 4 ] do echo Hi a=`expr $a + 1` done

FOR LOOP
For control_variable in value1 value2 value3 Do Command1 Command2 Done Usage:SS45 [arg1 arg2 arg3] For a in $* Do Echo $a Done $SS45 Merry go around EG:- Let us print names of all subdirectories present in the current directory. For entry in * Do If [-d $entry ]

Then Echo $entry Fi done


Example 1 $cat data 8 15 25 $cat express count=0 tot=0 for a in `cat data` do tot=`expr $tot + $a` count=`expr $count + 1` done avg=`expr $tot / $count` echo "The average is $avg" $

For loop for a in `ls *.sql` do echo $a isql -Usa -Pxxx -Sq -i$a -o$a.out done

test command
Examples:
if [ $# != 3 ] then echo "\nksh rowcntchk.ksh < SERVER > <Password > <Flag>\n " means newline echo " Flag Value ===> should be 'S' 's' 'D' 'd'\n" exit ######\n

fi

SCRIPT_DIR=/home/sukumar SERVER=test123 if [ ! -d ${SCRIPT_DIR}/${SERVER} ] then mkdir ${SCRIPT_DIR}/${SERVER} chmod 775 * fi

Example :2 if [ $FLAG = 'S' -o $FLAG = 's' ] then if [ ! -d ${SCRIPT_DIR}/${SERVER}/bkup ] then mkdir ${SCRIPT_DIR}/${SERVER}/bkup mkdir ${SCRIPT_DIR}/${SERVER}/bkup/seeddata chmod 775 * else clear echo "\nSNAPSHOTS ALREADY TAKEN IN "${SCRIPT_DIR}/${SERVER}/bkup" directory\n " exit fi fi

Example :3 #### whether input parameter given or not TRUE : if no input parameter given. FALSE: if ip given if [ -z "$1" ] then a=`date +%d%m` echo "Without Argument" else a=$1 echo "Argument given" or #example1 if test -n "$1" then echo "$1" fi Example :4 Client_Check=$1 password=$2 Date_Of_Ind=$3 if [ -z $Date_Of_Ind ] then Date_Of_Ind="19000101" Fi Example 5

if [ ! -f ./allind.dat ] then echo " " echo " allind.dat is missing....Cannnot Proceed " echo " " exit fi Example 6 if [ $# != 3 ] then echo echo " Hello exit fi

&& [ $# != 2 ]

Example 7 if [ "$ans" != "Y" -a "$ans" != "y" ] then exit fi Example 8 if [ ! -d ./${client} ] then echo "./${client} directory not created" exit fi

Example 9 isql -Usa -P$password -S$client -o./$client/tmp/chk.out << ! sp_who go ! errstat=$? if [ $errstat -gt 0 ] then cat ./$client/tmp/chk.out echo "Cannot connect server....." exit fi Example 10 - display variables, up to three if [ "$#" -gt 3 ] then echo "You have given too many variables." exit $# fi

Example 10 if [ "$#" -gt 3 ] # see if more than three variables are given then echo "You have given more than three variables." exit fi echo $* if test -n "$2" then shift echo $* fi

It would perform as follows:


$ example11 one one $ $ example11 one two one two two $ $ example11 one two three one two three two three three $ SHIFT

.4.3

Shift

The shift command promotes each of the command-line arguments. The second argument, represented by $2, is now the first argument, represented by $1. The third becomes the second and so on until the last argument becomes the next to last. You can access only the first nine command-line arguments (as $1 through $9). The shift command gives you access to the tenth, and the first becomes unavailable. There is no "unshift" command that will return the arguments that are no longer available. Sample Session: $cat demo_shift echo 'arg1='$1 ' shift echo 'arg1='$1 '

arg2='$2 ' arg2='$2 '

arg3='$3 arg3='$3

shift echo 'arg1='$1 ' arg2='$2 ' shift echo 'arg1='$1 ' arg2='$2 ' shift $demo_shift Richard Kathleen arg1=Richard arg2=Kathleen arg1=Kathleen arg2=Douglas arg1=Douglas arg2= demo_shift: cannot shift HOSTNAME: Echo #!/bin/sh .profile export

arg3='$3 arg3='$3 Douglas arg3=Douglas arg3= arg3=

SED command Environmental variables To delete all the lines that contain the regular expression
g/regular/d

NOTE: Note the different meanings of "g." The "g" at the beginning is the global command that means make the changes on all lines matched by the address. The "g" at the end is a flag that means change each occurrence on a line, not just the first. The -e option is necessary only when you supply more than one instruction on the command line. It tells sed to interpret the next argument as an instruction. When there is a single instruction, sed is able to make that determination on its own There are three ways to specify multiple instructions on the command line: Separate instructions with a semicolon. sed 's/ MA/, Massachusetts/; s/ PA/, Pennsylvania/' list Precede each instruction by -e. sed -e 's/ MA/, Massachusetts/' -e 's/ PA/, Pennsylvania/' list

how to find home directory

jrc1qsasp01 /home/sukumar:cat /etc/passwd | grep anirmala anirmala:x:29452:10004:Anoop Nirmala:/export/home/anirmala:/bin/ksh jrc1qsasp01 /home/sukumar: or jrc1qsasp01 /home/sukumar:echo $HOME /home/sukumar

NAME
test - check file types and compare values

SYNOPSIS
test EXPRESSION [ EXPRESSION ] test OPTION

DESCRIPTION
Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true [-n] STRING the length of STRING is nonzero -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2

INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -h FILE FILE exists and is a symbolic link (same as -L) -G FILE FILE exists and is owned by the effective group ID -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and is readable -s FILE FILE exists and has a size greater than zero -S FILE

FILE exists and is a socket -t [FD] file descriptor FD (stdout by default) is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and is writable -x FILE FILE exists and is executable Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING.

SEE ALSO
The full documentation for test is maintained as a Texinfo manual. If the info and test programs are properly installed at your site, the command info test should give you access to the complete manual.

Você também pode gostar