Introduction To Unix and Linux For Developer
Introduction To Unix and Linux For Developer
Essentials for
Developers
Introduction to Linux and Unix
Reference
Files
Hardware
Processes
Kernel
Shell
User
Hardware:
Is the base hardware on which Linux OS is installed.
Files
Hardware
Processes
Kernel
Shell
User
Kernel:
Hub of OS, allocates time and memory to programs.
handles file stores and communications in response to the system calls.,
Linux uses Monolithic kernel – Direct access to H/W, process communication easier.
Information Security Level 1 – Confidential
9 © 2012 – Proprietary and Confidential Information of Amdocs
How does Linux work?
Files
Hardware
Processes
Kernel
Shell
User
Shell:
Interface between User and Kernel.
After login, the program checks for user id and password.
starts the command line interpreter.
Interprets the commands written by the user.
Information Security Level 1 – Confidential
10 © 2012 – Proprietary and Confidential Information of Amdocs
How does Linux work?
Files
Hardware
Processes
Kernel
Shell
User
User:
Since it’s a multiuser OS, different users needs to have different User id
and passwords to connect to the OS.
This can be done by terminal emulator like Putty etc.
Information Security Level 1 – Confidential
11 © 2012 – Proprietary and Confidential Information of Amdocs
Linux Distributions
User/client login
● Bourne again shell (bash) is from free software foundation. It is very much
similar to Ksh & has C shell features plus command line editing & built in help
command.
● Z shell (zsh) is hybrid of all shell which is having feature of almost all the shell
combine.
<command_1> | <command_2>
● Using redirection operator will create a new file with the name given
on the right.
● Combination:
● $ls | head
● Tail prints the last N number of lines from the given input
files. Default is 10 lines.
Information Security Level 1 – Confidential
18 © 2012 – Proprietary and Confidential Information of Amdocs
Head and Tail Options.
● Tail is effective for viewing logs on the screen.
● $tail -n 5 <filename> - prints the last 5 lines.
● $tail -f <filename> - prints the appended lines as the file grows.
● Reference: http://www.theunixschool.com/2012/08/linux-sort-command-examples.html
UNIX kernel.
● E.g. date, ls, echo
● This will include aliases, path variables etc. which is what we call
the environment.
#!/bin/ksh
# This is a comment
1. /export/home/user/script.sh
2. ./script.sh &
$script.ksh 27 Delhi
#!/bin/ksh
your age : $1
your city : $2
● E.g.
● How will you print the 5th line of /etc/passwd file with the help of head and tail
command combination?
● Find out all the files named “core” from the entire server and remove them.
Reference:
3) ls: List of files and directories. (ls) (ls –a) (ls –ltr) (ls –l) (ls –ld)
4) cp: Copy file or directory. (cp –R <> <>) (cp <> <>)
5) mv: Move file or directory. (mv <> <>)
6) rm/rmdir: Remove a file or directory. (rm <>) (rm –rf <>) (rmdir <>)
7) touch: Create a blank file. (touch <>)
8) cat: concatenate file. (cat <>)
9) less/more: view the file. (less <>) (more <>)
10) File: Writes the type of the file.
Information Security Level 1 – Confidential
38 © 2012 – Proprietary and Confidential Information of Amdocs
Manipulating Directories and Files.
Demo and Practice for below commands for Directories:
1) mkdir: Make Directory. (mkdir <>) (mkdir –p <>)
2) which: Full PATH of the command. (which <>).
3) whereis: Locates source binary for program. (whereis <>).
Vi Editor modes:
1) Command Mode (Default mode)
2) Insert Mode.
3) Last Line Mode.
● Check where the binary of the command you used in the first step is present.
● Copy the file /etc/passwd to your temp directory using Relative PATH.
● Rename it as mywork.
● Long list this file to check details. Check the time stamp.
● Search for root in the mywork from last line mode. Check for occurrences.
Which permissions?
2) Read. – represented by ‘r’.
3) Write. – represented by ‘w’.
4) Execute. – represented by ‘x’.
1) First digit – Type of file, - for regular, d for directory, l for link.
2) First set – Owner.
3) Second set – Group.
4) Third set – Others.
File System
What is a link?
1) File has I-node which stores information about file.
2) Filename is simply a reference to this data.
3) Link is a way to refer to contents of a file.
Two Types:
4) Hard Link.
5) Soft Link.
a-file.txt
Data on Disk
b-file.txt
Reference: http://www.ugrad.cs.ubc.ca/~cs219/CourseNotes/Unix/commands-links.html
Information Security Level 1 – Confidential
55 © 2012 – Proprietary and Confidential Information of Amdocs
Soft Link
Symbolic link: file which contains the name of another file.
Access contents of the file through link.
Command: $ln –s a-file.txt b-file.txt
Cannot modify contents of a-file.txt from b-file.txt.
Deleting b-file.txt doesn’t have any impact on a-file.txt.
a-file.txt
Data on Disk
b-file.txt
Reference: http://www.ugrad.cs.ubc.ca/~cs219/CourseNotes/Unix/commands-links.html
e.g.
NAME=Zara
echo $NAME
Variable Description
$$ 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.
NAME=ZaraZara
echo ${#NAME} #length of string
echo ${NAME}Za #Append charecters
STATES=8
1. echo $(( STATES += 4 ))
2. STATES=$((STATES + 4))
3. STATES=`expr $STATES + 4`
echo $STATES
+ Addition - Adds values on either side of the operator `expr $a + $b` will give 30
- Subtraction - Subtracts right hand operand from left `expr $a - $b` will give -10
hand operand
* Multiplication - Multiplies values on either side of `expr $a \* $b` will give 200
the operator
/ Division - Divides left hand operand by right hand `expr $b / $a` will give 2
operand
% Modulus - Divides left hand operand by right hand `expr $b % $a` will give 0
operand and returns remainder
= Assignment - Assign right operand in left operand a=$b would assign value of b into a
== Equality - Compares two numbers, if both are same [ $a == $b ] would return false.
then returns true.
!= Not Equality - Compares two numbers, if both are [ $a != $b ] would return true.
different then returns true.
-eq Checks if the value of two operands are equal or not, if yes [ $a -eq $b ] is not true.
then condition becomes true.
-ne Checks if the value of two operands are equal or not, if values [ $a -ne $b ] is true.
are not equal then condition becomes true.
-gt Checks if the value of left operand is greater than the value of [ $a -gt $b ] is not true.
right operand, if yes then condition becomes true.
-lt Checks if the value of left operand is less than the value of [ $a -lt $b ] is true.
right operand, if yes then condition becomes true.
-ge Checks if the value of left operand is greater than or equal to [ $a -ge $b ] is not true.
the value of right operand, if yes then condition becomes
true.
-le Checks if the value of left operand is less than or equal to the [ $a -le $b ] is tr
value of right operand, if yes then condition becomes true.
-t file Checks if file descriptor is open and associated with a terminal if [ -t $file ] is false.
yes then condition becomes true.
-u file Checks if file has its set user id (SUID) bit set if yes then condition [ -u $file ] is false.
becomes true.
-r file Checks if file is readable if yes then condition becomes true. [ -r $file ] is true.
-w file Check if file is writable if yes then condition becomes true. [ -w $file ] is true.
-x file Check if file is execute if yes then condition becomes true. [ -x $file ] is true.
-s file Check if file has size greater than 0 if yes then condition becomes [ -s $file ] is true.
true.
-e file Check if file exists. Is true even if file is a directory but exists. [ -e $file ] is true.
● Find file that match a given set of parameters, ranging from the file’s name to its
modification date
● Looks at every file, one at a time.
● Uses the information in the file’s inode to evaluate an expression given by the command-line operators.
● Takes the specified action (e.g., printing the file’s name) if the expression’s value is “true.”
● Syntax :
● Find path operators [Action ] – here path is one or more directories in which find will
begin to search & operators tells find which file you are interested in.
Operators description
-name filename Find files with the given filename.
-perm mode Find files with the given access mode. You must give the access mode in octal.
-type c Find the files of the given type, specified by c. c is a one-letter code; for example, f for a plain
file, b for a block special file, l for a symbolic link, and so forth.
-user name Find files belonging to user name
-group name Find files belonging to group name
-size n Find files that are n blocks long. A block usually equals 512 bytes.
-inum n Find files with the inode number n.
-mtime n Similar to -atime, except that it checks the time the file’s contents were modified.
-ctime n Similar to -atime, except that it checks the time the inode was last changed. “Changed” means
that the file was modified or that one of its attributes (for example, its owner) was changed.
-newer file Find files that have been modified more recently than file.
● Action :
● -print – print the file names on the standard output
● -ls - list the file names on the standard output
● -exec - To include the pathname of the file that’s just been found in command, use the special symbol {}.
command must end with a backslash followed by a semicolon (\;)
● Example : find . -name "*.o" -exec rm -f {} \;
● -ok - Same as -exec, except that find prompts you for permission before executing command
● ls -l `find . -print` - list of file found by find command however this may generate error when the command line is too
large
● An alternate method uses the xargs command. xargs and find work together beautifully. xargs executes its
arguments as commands and reads standard input to specify arguments to that command
● find / -print | xargs ls –lrt – print all the files from root directory
● find . -name \*.sh –print or find . –name ‘*.sh’ –print to print all script in your home directory
● find . -type f -atime +30 –print check the files which has not been read in last 30 days.
● find . -atime 1 -name '*.sh' –print tell what are the script being modified in last one days
● find . \! \( -atime 1 -name '*.sh' \) –print just opposite to what we said above
● find . -type f -atime 1 | xargs ls –lrt file which are older then one day.
● Let’s say you want to find the files after a specific time say 10 th April 09:00 AM.
● First you create a file with old time stamp touch –t mmddhhmm <file name>, touch -t 04091500 past_time, touch -t 04101500
past_time1
● find . -newer ./past_time | xargs ls –lrt find the files which are created after the past_time creator
● find . \! -newer ./past_time | xargs ls –lrt find file older then a specified time.
● find . -newer ./past_time \! -newer ./past_time1 | xargs ls –lrt to find the files between two specified time.
● find . -perm 20 | xargs ls –lrt find file where group has write permission
● find . -perm -100 –print find files were owner can execute
● Some time you accidently create a file with a space or some control character in the name which you can not delete
so you use the –inum to find & delete the file
● find . -size 4096c –print to fine the files of specified size (its always advised to give the size in bytes)
● find . size +72c -size -4096c | xargs ls –lrt find the files which are larger then 72byte & smaller then 4096 bytes.
● find . -group emas | xargs ls –l find a files which are owned by emas group
● find . -user ranjitkumarr | xargs ls –l find the files which are owned by user
● case statement
● break
● exit
● continue
● functions
if [ -e /etc ]
then
echo “etc directory exists”
else
echo “This will never run”
fi
----------------------------------------------
if [ 22 –ne 11 ]; then
echo “Numbers are not equal”
elif [ `whoami` != ‘root' ]; then
echo “You are not Root”
fi
for i in 1 2 3 4 5
do
echo "Welcome $i“
done
count=0
while [[ $count -lt 10 ]];
do
print "count is $count"
(( count += 1 ))
done
CMG=“Coming”
DEC=“Not Coming”
case $VAR in
john) print $CMG;;
fred) print $CMG;;
martin) print $DEC;;
*) print "Wrong name...";;
esac
● function print {
● print () {
subfunc(){
typeset var
var=2
echo “variable is now $var”
}
var=1
echo “var starts as $var, before calling subfunc”
subfunc # call the function
echo “var after function is now $var”
name(){
arg1=$1
arg2=$2
echo $arg1
}
name foo bar
● awk '1' employee.txt other way to print all lines from the files.
● awk -F"," '{print $1}' awk_example print first fields where fields are separated by comma
● awk '{print $1,$2}' FS="," awk_example print files with file separator as comma
● awk -F"," 'NR!=1{print $1,$3}' OFS="," awk_example print output field separated by comma (OFS- output field
separatror)
● awk -v q="'" '{print q $0 q}' awk_example1 to pass argument using awk
● awk '$0 ~ /Neha/{print}' awk_example ~ is the symbol used for pattern matching. The / / symbols are used to
specify the pattern. If the line($0) contains(~) the pattern Neha, print the line.
● awk -F, '$1 ~ /Neha/' awk_example search Neha in the first fields separated by comma
● awk -F" " '$5>6000' employee.txt print the employee whose salary is more than $6000
● It’s a very powerful tool when it comes to file formatting. It can group data based on a column/field.
● awk -F" " '{x+=$5}END {print x}' employee.txt to find the sum of all employee salary
● awk -F" " '$4=="Technology" {x+=$5}END {print x}' employee.txt find the sum of salary of employee who division is technology
● awk -F, '{print > $1}' awk_file_split split the files into various files depending upon first field
● awk -F, '{print > $1".txt"}' awk_file_split split the file by having .txt to the new file names.
● awk -F, '{if($2<=500)print > "500L.txt";else print > "500G.txt"}' awk_file_split split the file depending upon the condition.
● awk 'NR%3==1{x="F"++i;}{print > x}' awk_file_split split the file in equal lines (The condition does the trick here: NR%3==1 : NR is
the line number of the current record. NR%3 will be equal to 1 for every 3rd line such as 1st, 4th, 7th and so on. And at every 3rd line,
the file name is changed in the variable X)
● awk -F"," '{$1=++i FS $1;}1' OFS=, awk_file_split insert a new column before the first column ($1=++i FS $1 => Space is used to
concatenate columns in awk. This expression concatenates a new field(++i) with the 1st field along with the delimiter(FS), and
assigns it back to the 1st field($1))
● awk -F, '{$(NF+1)=++i;}1' OFS=, awk_file_split insert a column after last column in a file ($NF indicates the value of last column.
Hence,by assigning something to $(NF+1), a new field is inserted at the end automatically.)
● awk -F, '{$(NF-1)=++i FS $(NF-1);}1' OFS=, awk_file_split insert the records before the second last two columns (NF-1
points to the 2nd last column. Hence, by concatenating the serial number in the beginning of NF-1 ends up in inserting a
column before the 2nd last)
● awk -F, '{$2+=10;}1' OFS=, awk_file_split update second column by adding 10 to each variable
● awk -F, '{$1=toupper($1)}1' OFS=, awk_file_split convert the first column to upper case.
● awk -F, '{$1=substr($1,0,3)}1' OFS=, awk_file_split extract the first three character from the first field
● awk -F, '{$2="";}1' OFS=, awk_file_split Empty the value in the second column
● awk -F, '{for(i=1;i<=NF;i++)if(i!=x)f=f?f FS $i:$i;print f;f=""}' x=2 awk_file_split / awk -F" " '{for(i=1;i<=NF;i++)if(i!=x)f=f?f FS $i:
$i;print f;f=""}' x=2 employee.txt Remove/delete the second column
(By just emptying a particular column, the column stays as is with empty value. To remove a column, all the subsequent
columns from that position, needs to be advanced one position ahead. The for loop loops on all the fields. Using the ternary
operator, every column is concatenated to the variable "f" provided it is not 2nd column using the FS as delimiter. At the end,
the variable "f" is printed which contains the updated record. The column to be removed is passed through the awk variable "x"
and hence just be setting the appropriate number in x, any specific column can be removed.)