Unix.pptx
Unix.pptx
Rea
d data
file
cat a
cat<a
paste a
grep ‘.*’ a
cut –c1- a
while loop
xargs –L1 a
sed ‘’ a
sed –n ‘p’ a
sed –n ‘1,$p’ a
awk ‘1’ a
UNIX C
omman
d Line S
tructur
e
Where
- option indicates the functionality of the command and an
- argument indicates on what the command is to perform its action, usually a file or series of files.
%
week number, Sunday as first day of week 00–53
U
%
week number, Monday as first day of week 00–53
W
%
two-digit month number 01–12
m
%h month name, abbreviated Sep
%b month name, localised abbreviation Sep
%
locale's full month, variable length September
B
%C two century digits from year 00–99
%D mm/dd/yy 09/15/14
%F %Y-%m-%d 2014-09-15
date C
omma
nd
date --date="yesterday"
Options:
exist already.
-v Display each directory that mkdir creates. Most often used with -p.
Options:
-p Remove all the directories in sequence till it finds non empty directory.
directory is non-empty.
File A
cces
s Per
miss
ions
chmod –c, --changes Like --verbose, gives verbose output only when a change is actually
made.
chmod –v, --verbose Verbose mode; output a diagnostic message for every file
processed.
chmod –reference=RFILE Set permissions to match those of file RFILE.
chmod –R <<directory>>Recursively descend through the directory structure and change the mode.
chmod -f Suppress error messages if command fails.
File M
ainten
ance C
omma
nds
touch
✔ Creates an empty file if the file does not exists
✔ Updates the access and modification times of each FILE to the current system time.
cp
Copies file/files from one location to other.
cp [options] old_filename new_filename
cp –u,--update Copy only when the SOURCE file is newer than the destination
file or the destination file is missing.
mv
move/rename file/files from one location to other.
mv [options] old_filename new_filename
-u,--update
Links
Hard Link
A hard link is a pointer to the file's i-node
Soft/symbolic/symlink
pointer to the original file
no physical data storage been created
• Soft Links:
Soft Links can be created across file systems.
Soft link has a different inode number than the original file.
On deleting the original file, soft link cannot be accessed.
Soft link needs extra memory to store the original file name as its data.
Source file need not exist for soft link creation.
Can be created on a file or on a directory.
Access to the file is slower due to the overhead to access file.
• Hard Links:
Hard links can be created only within the file system.
Hard links have the same inode number as the original file.
On deleting the original file, hard linked file can still be accessed.
Hard links do not need any extra data memory to save since it uses links
Source file should exist.
Can be created only on files, not on directories.
Access to the file is faster compared to soft link.
Display
comma
nds
cat
Options:
-n Precede each line output with its line number.
-s Suppress messages if files do not exist.
-v Display control characters and nonprinting characters
-sn - Don’t Display Repeated Empty Output Lines
-e$ is printed at the end of each line. This option must be used with -v.
Watch command
Wc –
word
count
wc
spcount lines, words, and characters in a file. Character
count includes ace, tabs and newline character.
options:
-c Displays only number of characters
-l Displays only number of lines
-w Displays only number of words
-L output length of longest line
File R
e direc
tion
File Descriptors
stdin 0 Standard input to the program
stdout 1 Standard output from the program
stderr 2 Standard error output from the program
Wildcar
d Chara
cters
3 Modes
Insert
Command and
Execute
Insert Execute
esc esc
i,I,a,A,o,O :wq, q!
R,R,s,S Command
VI Ed
itor
-R Read-only
+ Position on last line of file in vi.
+n Position on n line of the file in vi.
VI –
Mod Insert
e
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 places into the file .
Command Mode:
This mode enables you to perform administrative tasks such as saving files, executing commands, moving the
cursor, cutting and pasting lines or words, and finding and replacing. In this mode, whatever you type is interpreted
as a command.
Execute Mode:
:q quit
:w save
:wq save and quit
:w filename save into different file
:n Move to nth line of the file – equal to nG of command mode
:f filename Renames current file to filename.
:e filename Opens another file with filename.
:cd dir Changes current working directory to dirname
:e # Use to toggle between two opened files.
:n In case you open multiple files using vi, use :n to go to next file in the series.
:N Use :N to go to previous file in the series.
:r file Reads file and inserts it after current line
:nr file Reads file and inserts it after line n.
:q! quit without save
:e! combination of q! + vi <<filename>>
VI – E
xecu
te Mod
e
/ search pattern
n forward search
N backward search
Set commands:
:set ic Ignores case when searching
:set nu Displays lines with line numbers on the left side
:set list Show invisible characters
echo
repeat, or echo, the argument you give it back to the standard output device
Options:
✔ -n suppress print <new-line>
✔ \c suppress print <new-line>
✔ \t tab
✔ \n new-line
✔ Echo * - print all the files and folders in a directory
read reads from the input
read only The shell provides a way to mark variables as read-only by using the read only command. After a
variable is marked read-
only, its value cannot be changed.
echo
& re
ad c
omm
ands
• Colored output of echo command
• echo command can change the font style, background color of fonts and font colors. Escape sequence \033 can be
used to alter font properties. -e option has to be used in order to the escape sequence be in effect.
• [0m: Normal
[1m: Bold fonts
[2m: Font color changes to Purple
[4m: Underlined fonts
[7m: Invert foreground and background colors
[8m: Invisible fonts
[9m: Cross lined fonts
[30m: Font color changes to Grey
[31m: Font color changes to Red
[32m: Font color changes to Green
[33m: Font color changes to Brown
[34m: Font color changes to Blue
[35m: Font color changes to Violet
[36m: Font color changes to Sky Blue
[37m: Font color changes to Light Grey
[38m: Font color changes to Black
[40m: Background color changes to Black
[41m: Background color changes to Red
[42m: Background color changes to Green
[43m: Background color changes to Brown
[44m: Background color changes to Blue
[45m: Background color changes to Violet
[46m: Background color changes to Sky Blue
[47m: Background color changes to Light Grey
Proc
esse
s
When you start a process (run a command), there are two ways you can run it:
Foreground Processes
background Processes
Foreground Processes:
By default, every process that you start runs in the foreground. It gets its
input from the keyboard and sends its output to the screen.
background processes:
While a program is running in foreground and taking much time, we cannot run any other commands (start
any other processes) because prompt would not be available until program finishes its processing and comes
out.
sample.ksh &
Proc
esse
s
Stopping Processes:
Ending a process can be done in several different ways. Often, from a console-based command, sending a
CTRL + C keystroke (the default interrupt character) will exit the command. This works when process is running in
foreground mode.
If a process is running in background mode then first you would need to get its Job ID using ps command and
after that you can use kill command to kill the process.
nohup No hangup
nohup sample.ksh &
sleep
sleep for the specified number of seconds
wait
ZIP
gzip
zip the specified file
gzip –c If you want to retain the original file even after compression or want the .gz file to have a different
name
gzip –dc To view the contents of the file without completely decompressing the file
cat dump.doc file1 test.sh | gzip > all.gz – To compress data from multiple files
tar
tar It can create a single file with the contents of a directory structure in one path or extract a file
into directory structure in another path.
tar –cvf <<tar name>> <<dir>> - to tar the directory dir
Instead of giving entire directory name as a parameter to create a tar file, a list of files
which care to be archived can be passed to tar with -L option.
Sometimes you may need to exclude files from the tar archive. To do this place the files and directories to be excluded in a list file and
then use tar –X <exclude-list>.
tar –tvf
The contents of the tar file cannot be viewed directly by cat or more , but to view the details of the files and directories contained in the
tar file
Recursively search the indicated directory tree to find files matching a type or pattern you specify.
find <<directory>> <<pattern>> <<value>> <<action>>
uniq
uniq filters duplicate adjacent lines from a file.
uniq [options] file
if [[ <<expression>> ]];
then
<<do some actions>>
elif [[ ]]
else
<<do some other actions>>
fi
File test operators:
-f file exists and a regular file
-r/-w/-x file exists and is readable/is writable/is executable
-s check for file size
-e Check if file exists. Is true even if file is a directory but exists.
String operators:
-z string Length of string is zero
-n non zero
String1 == string2 string1 is identical to the string2
case
for The for loop executes a block of statements once for each member of a list
for I in <<list>>
do
<<commands>>
done
while While command repeats a block of commands based on the result of a logical test.
while read ln
do
<<commands>>
done<file.dat
hist
ory
com
mand
break
breaks and will come out from the while or for loops.
Break 2 – for nested loops and come out of outer loops.
Continue
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.
grep u
tility
The grep utility is used to search for generalized regular expressions occurring in Unix files.
grep [options] [file[s]]
Options
-i ignore case
-c report only a count of the number of lines containing matches
-v invert the search, displaying only lines that do not match
-n display the line number along with the line matched line
-w entire word
-l Display the filenames, but do not display the matched lines.
-L Display all the files which do not contain the matched string/pattern.
-o –b Displaying the position of the matched string in the line
-h Display the matched lines, but do not display the filenames.
-A Display specified number of lines after the matching line
-B Display specified number of lines before the matching line
-C Display specified number of lines before and after the matching line
grep u
tility
grep OR operatins:
You have many occurrences of a pattern in a line and you want to replace just the nth pattern or all n+1,n+2..
occurrences . use a number after the ending “/”.
If you need to replace all occurrences starting from 2nd,then use the following command.
$ echo "1st 2nd 3rd 4th 5th 6th"|sed "s/[0-9]th//2g“
sed
Util
ity
sed –n ‘100,400p’
sed –n -e ‘1p’ –e ‘$p’
sed –n ‘/unix/p’
sed –n ‘1p;1q’ file - interpret only till 1st line
sed –n “${start-line} , ${end-line}p”
sed –n ‘/’$ptrn‘/,15p’ general-dates.prt
sed ‘1,4d’
sed ‘4,+5d’ This will match line 4 in the file, delete that line, continue to delete the next five lines, and then cease its deletion
and print the rest
sed‘2,5!d’ This will delete everything except starting from 2nd till 5th line.
sed‘1~3d’ This deletes the first line, steps over the next three lines, and then deletes the fourth line. sed continues applying this
pattern until the end of the file.
sed -e 's/^[[:digit:]][[:digit:]][[:digit:]]/(&)/g' phone.txt - Ampersand referencing
sed 's@/usr/bin@&/local@g' path.txt
sed 's@^.*$@<<<&>>>@g' path.txt - Match the whole line
sed
Util
ity
index(string,search)
length(string)
split(string,array,separator)
substr(string,position)
substr(string,position,max)
tolower(string)
toupper(string)
at & cro
ntab
at:
Is used to schedule commands to be executed once, at a particular time in the future.
at 1145 jan 31 abc.ksh
The atq program lists the currently queued jobs, while atrm removes jobs from the queue
-m to email once the job is finished.
Crontab:
which is used for recurring executions (e.g. once an hour, every Tuesday, January 1 every year)
# * * * * * command to execute
#│││││
#│││││
# │ │ │ │ └───── day of week (0-6)(0-6 are Sunday-Saturday, or use names; 7 is Sunday,
same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)
Mis
cella
neo
us c
omm
and
s
du - The du command outputs the number of kilobyes used by each subdirectory. Useful if you have gone over quota and
you want to find out which directory has the most files.
du -s * The -s flag will display only a summary (total size)
Spe
cial
vari
a bles
• function_name ()
{ list of commands }
Sample scripts
• Fabonacci series
• Star output
• Write multiple files scenario
• sub_mark.ksh
• cp_multi.ksh multi file copying
• Sum up the numbers from a given number (123 – 1+2+3)