Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Unix Commands

Uploaded by

Himani Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unix Commands

Uploaded by

Himani Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Unix Commands

Dr. Sarvesh Tanwar


Commands
• Who
• Whoami
• Cat > fn
• Cat fn
• Cat fn1 fn2 >newfn
• Cat fn1 fn2 >>newfn
• Cp fn1.txt fn2.txt

2
• Cat
• Cd
• Ls
• Mkdir
• Rm--Removes (Deletes) filename
• Rmdir--Deletes an existing directory provided it is empty
• Man- man ls
• more

3
rm

Command Explanation
Removes both the parent and child
rmdir –p
directory
Removes all the parent and
rmdir –pv subdirectories along with the
verbose.

4
cd
• This command is used to change the current working directory of the
user.

Command Explanation

This command also changes the


cd ~
directory to home directory
Changes the directory to root
cd /
directory
Changes the directory to its parent
cd ..
directory
We specify the folder name in
cd ‘xx yy’ inverted commas because there is a
space in the folder name

5
• Pwd
• Cal
• Cat
• Touch
• Cp
• Banner [sudo apt install banner]

6
Date
Format options Purpose of Option Output

Displays Weekday name in short (like


date +%a Mon, Tue, Wed) Thu
Displays Weekday name in full short
date +%A (like Monday, Tuesday) Thursday
Displays Month name in short (like Jan,
date +%b Feb
Feb, Mar )
Displays Month name in full short (like
date +%B January, February) February
date +%d Displays Day of month (e.g., 01) 07
Displays Current Date; shown in
date +%D 02/07/13
MM/DD/YY
date +%F Displays Date; shown in YYYY-MM-DD 2013-02-07
date +%H Displays hour in (00..23) format 23
date +%I Displays hour (01..12) format 11
date +%j Displays day of year (001..366) 038

7
date +%m Displays month (01..12) 02
date +%M Displays minute (00..59) 44
date +%S Displays second (00..60) 17
Displays nanoseconds
date +%N 573587606
(000000000..999999999)
Displays time; shown as HH:MM:SS
date +%T 23:44:17
Note: Hours in 24 Format
Displays day of week (1..7); 1 is
date +%u 4
Monday
Displays week number of year, with
date +%U 05
Sunday as first day of week (00..53)
date +%Y Displays full year i.e. YYYY 2013
alphabetic time zone abbreviation
date +%Z IS
(e.g., EDT)

8
ls
ls –a
ls -s: print the allocated size of each file
Ls t*
Ls ?est
Ls /dir1/*t
Ls [aeiou]* [start with vowels]
Ls [!aeiou]* [not start with vowels]

9
• Ls [a-d][c-z][4-9]??

This will list all 5 character filenames in the current directory whose
first character is in the range a to d, the second character is in the range
c to z, the third character is in the range 4 to 9, whereas the fourth and
fifth are any valid characters.

• Ls –l
• The dot (.) is a mapping to itself and the dotdot (.) is a mapping to the
parent directory.
10
Command Explanation

ls <path name> By specifying the path after ls, the content in that path will be displayed

Using ‘l’ flag, lists all the contents along with its owner settings, permissions & time
ls –l
stamp (long format)

ls –a Using ‘a’ flag, lists all the hidden contents in the specified directory

Using ‘–author’ flag, lists the contents in the specified directory along with its
ls –author
owner

ls –S Using ‘a’ flag, sorts and lists all the contents in the specified directory by size

ls *.html Using ‘*’ flag, lists only the contents in the directory of a particular format

ls –lS > file.txt Using ‘>’ flag, copies the result of ls command into a text file

11
Command Explanation

This is used to add line numbers to non-blank


cat -b
lines

cat -n This is used to add line numbers to all lines

cat -s This is used to squeeze blank lines into one line

cat –E Show $ at the end of line

12
• rm –i fn [confirmation before deleting the files]
• rm –r dir [ empty the directory]
• -f [forcefully delete all files]

Command Explanation
Removes even non-empty
rm –r
directories.
Removes non-empty directories
rm –rp including parent and
subdirectories.

13
• mv test demo [rename the file, directories]
• mv dir1 newdir1

Command Explanation
Enters interactive mode; CLI asks
mv -i
before overwriting files
Updates the destination file only
mv -u when the source file is different
from the destination file
Verbose; Prints source and
mv -v
destination files

14
grep
• Print lines matching a pattern
• grep “hello” f1.text
• -I : case insensitive search
• -n : show the line# along with matched line
• -v : invert match e.g. finds all lines that do not match
• -w : match entire words, rather than substrings
• -c: Displaying the Count of Number of Matches Using grep
• *: Display the File Names that Matches the Pattern Using grep [grep -l
"unix" *] or grep -l "unix" f1.txt f2.txt f3.xt f4.txt
• -v: Displaying only the matched pattern Using grep 15
• Matching the Lines that Start with a String Using grep
• The ^ regular expression pattern specifies the start of a line. This can
be used in grep to match the lines which start with the given string or
pattern.
grep "^unix" geekfile.txt
• Matching the Lines that End with a String Using grep
• The $ regular expression pattern specifies the end of a line. This can
be used in grep to match the lines which end with the given string or
pattern.
grep "os$" geekfile.txt

16
• Specifies expression with -e option
• Can use multiple times :
grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt

17
• $ grep “g[ood]” file_name
• $ grep “h..e” file_name
• $ grep “[0-9]” file_name
• http://www.complexsql.com/grep-command/

18
Options Description
This prints only a count of the lines that
-c
match a pattern

Display the matched lines, but do not


-h display the filenames.

–i Ignores, case for matching

-l Displays list of a filenames only.

Display the matched lines and their line


-n numbers.

This prints out all the lines that do not


-v matches the pattern

-w Match whole word

19
Word count
• wc –l f1.txt
• -l : no. of lines
• -w: no. of words
• -c: no. of characters
• W-max character length

20
File’s command
• file filename [Identifies the file type (binary, text, etc) ]
• head filename [Shows the beginning of a file]
• head –n 3 file
• tail filename [Shows the end of a file]
• which filename [Shows the location of a file if it is in your PATH]
• whereis filename [Shows the location of a file]

21
Calculator – base conversion
• bc
• 10/2*2
• Sqrt(225)
• Scale=1
• 2.25+1= 3.35
• for(i=1;i<=10;i++)i
• quit

22
• expr (100+200)
• expr (3\*2)
• factor
• 15
• To quit-q

23
Sorting
• sort filename
• sort f1 f2 f3
• sort –o file f1 f2 f3 [-o: output]
• sort –u –o file f1 f3 [-u: unique]
• sort –m f1 f2 [-m: merge]
Command Explanation
the flag returns the results in reverse
sort -r
order;
sort -f the flag does case insensitive sorting
the flag returns the results as per
sort -n
numerical order
24
cut
• Cut: In computing, cut is a Unix command line utility which is used to
extract sections from each line of input — usually from a file.
• Cut –b 1,2 file1 [-b= byte]
• Cut –b 1,2,3 file1
• Cut –b 1-2 file1
• Cut –b 1-2,4-5 file1
• cut –b 1- file1 [1- indicate from 1st byte to end byte of a line]
• Cut –b -3 file1 [-3 indicate from 1st byte to 3rd byte of a line]

25
• Cut –c 2 file1
• For delimiter separated fields, the -d option is used. The default
delimiter is the tab character.
• $ cut -d “,” -f 2,6 file1

26
Process
• $ ps -ef [Show every process running, formatted as a table]
• $ top [Show a live view of all current processes]
• bg - resume a background suspended a job
• $ cat>1
Ctrl-Z
• $ bg
• jobs
• fg - bring a background job to the foreground
$ cat>1
Ctrl-Z
27
• Listing Running Processes
• Ps
• One of the most commonly used flags for ps is the -f ( f for full)
option, which provides more information
• Ps –f
• kill command terminates the first_one process. If a process ignores a
regular kill command, you can use kill -9 followed by the process ID as
follows −
• $kill -9 6738

28
Options with ps

Sr.No. Option & Description


1 -a
Shows information about all users
2 -x
Shows information about processes without terminals
3 -u
Shows additional information like -f option
4 -e
Displays extended information

29
• $ bg
$ fg
• To run the count program, which will display the process identification
number of the job, enter:
• count &

30
• sleep 5 To run a process in the background without
Stopping a process in between of itsgetting impacted by the closing of the
execution. To stop a foreground process interminal.
between of its execution we may press
CTRL+Z to force stop it. • nohup sleep 100 &

• sleep 100 • sleep 100&


• jobs
• bg • To run processes with priority.
• ps -ef | grep sleep • nice -n 5 sleep 100
• fg top

31
cp
This command copies files and directories. A copy of the file/directory copied, still remains in the working
directory.

syntax: $ cp <flag> {filename} /pathname/

Command Explanation
Enters interactive mode; CLI asks before overwriting
cp -i
files

cp -n Does not overwrite the file

Updates the destination file only when the source


cp -u
file is different from the destination file
Recursive copy for copying directories; Copies even
cp -R
hidden files

cp -v Verbose; Prints informative messages


32
• diff - Finding the Differences Between Two Files
• The diff command compares the contents of two files. The format of
diff is:-
• diff file1 file2

33
su
• This command is used to switch to root-user so that superuser
permissions can be used to execute commands.
syntax:
• $ su
• su <username>
• This command is used to switch to a different user whose name is
passed as the argument.
• $ su <username>

34
• User- You.
• Group- Anyone in the same class as yourself, such as pg 1999, staff or
postdoc.
• other - Anyone who uses the Institute Computers (sometimes called
world).

35
The permissions associated with each digit is as follows.

Number read write execute


0 – – –
1 – – yes
2 – yes –
3 – yes yes
4 yes – –
5 yes – yes
6 yes yes –
7 yes yes yes

36
Pipe
• The Pipe is a command in Linux that lets you use two or more
commands such that output of one command serves as input to the
next. In short, the output of each process directly as input to the next
one like a pipeline. The symbol '|' denotes a pipe.
• A pipe is a form of redirection (transfer of standard output to some
other destination) that is used in Linux and other Unix-like operating
systems to send the output of one command/program/process to
another command/program/process for further processing. The
Unix/Linux systems allow stdout of a command to be connected to
stdin of another command.

37
• $ls -l | grep “Aug”
• $ls -l | grep -i “carol.* aug”
• $ls -l | grep "Aug" | sort +4n
• $ls -l | grep "Aug" | sort +4n | more

38
• To avoid this, you can pipe the output of the 'cat' command to 'less'
which will show you only one scroll length of content at a time.
• cat filename | less
• 'pg' and 'more' commands
• cat Filename | pg
• cat Filename | more

39
• Listing all files and directories and give it as input to more
command.
$ ls -l | more
• Use sort and uniqe command to sort a file and print unique values.
$ sort record.txt | uniq
• Use head and tail to print lines in a particular range in a file.
$ cat sample2.txt | head -7 | tail -5

40
• Use cat, grep, tee and wc command to read the particular entry
from user and store in a file and print line count.
• $ cat result.txt | grep "Rajat Dua" | tee file2.txt | wc -l

41
Soft and Hard links in
Unix/Linux
• A link in UNIX is a pointer to a file. Like pointers in any programming
languages, links in UNIX are pointers pointing to a file or a directory.
Creating links is a kind of shortcuts to access a file. Links allow more
than one file name to refer to the same file, elsewhere.

There are two types of links :


• Soft Link or Symbolic links
• Hard Links

42
• A symbolic or soft link is an actual link to the original file, whereas
a hard link is a mirror copy of the original file.
• If you delete the original file, the soft link has no value, because it
points to a non-existent file. But in the case of hard link, it is entirely
opposite. Even if you delete the original file, the hard link will still has
the data of the original file. Because hard link acts as a mirror copy of
the original file.

43
• These links behave differently when the source of the link (what is
being linked to) is moved or removed. Symbolic links are not updated
(they merely contain a string which is the pathname of its target);
hard links always refer to the source, even if moved or removed.

• For example, if we have a file a.txt. If we create a hard link to the file
and then delete the file, we can still access the file using hard link. But
if we create a soft link of the file and then delete the file, we can’t
access the file through soft link and soft link becomes dangling.
Basically hard link increases reference count of a location while soft
links work as a shortcut (like in Windows)

44
Hard link
• Hard Links have the same inodes number.
• ls -l command shows all the links with the link column showing
the number of links.
• have actual file contents
• Removing any link, just reduces the link count but doesn't affect
the other links.
• You cannot create a Hard Link for a directory.
• Even if the original file is removed, the link will still show you the
contents of the file.has the actual contents of original file, so that you
still can view the contents, even if the original file moved or removed.
45
Steps for Creating Hard Link
Syntax
$ ln [original filename] [link name]
• Create a file called source.file with some contents
• $ cat source.file
• $ ln source.file hardlink.file
• $ cat hardlink.file
• $ ls –lia
We can see that both hardlink.file and source.file have the same
the inodes number (11665692) and file permissions (-rw-r--r--). Hence, it
is proved that hard link file shares the same inodes number and
permissions of original file. 46
• If we change the permissions on source.file, the same permission will
be applied to the hardlink.file as well.
Now, remove the original file (i.e source.file) and see what happens.
• $ rm source.file

Check contents of hardlink.file using command:


• $ cat hardlink.file

Can check Hard link shares the same inode number, the permissions and data of
the original file.
47
Soft link
• Soft Links have different inodes numbers.
• ls -l command shows all links with second column value 1 and the link
points to the original file.
• Soft Link contains the path for original file and not the contents.
• Removing soft link doesn't affect anything but when the original file
is removed, the link becomes a 'dangling' link that points to
nonexistent file.
• A Soft Link can link to a directory.has only the path of the original file,
not the contents.
Syntax
$ ln -s [original filename] [link name]
48
Steps for creating soft or symbolic
link
• Let us create an empty directory called "test".
• $ mkdir test
• Change to the "test" directory:
• $ cd test
• Now, create a new file called source.file with some data as shown
below.
• $ ln -s source.file softlink.file
• $ cat source.file
• $ cat softlink.file

49
• Let us check the inodes and permissions of softlink.file and source.file.
• $ ls –lia
• Can check soft link don't share the same inode number and
permissions of original file.

50
• soft link don't share the same inode number and permissions of
original file.
• $ cat softlink.file

51
Comparison between hard and soft
link
HARD LINK
BASIS FOR COMPARISON SOFT LINK
Basic A file can be accessed through many A file can be accessed through different
different names known as hard links. references pointing to that file is known
as a soft link.

Link validation, when the original file is Still valid and file can be accessed. Invalid
deleted

Command used for creation ln ln -s

inode number Same Different

Can be linked To its own partition. To any other file system even networked.

Memory consumption Less More

Relative Path Not applicable Allowed

52
log
• Logname command is used to display the login name of the user.
• $logname
• $id

53
uname
• The Uname command displays Operating system name.Like Red-
Hat,Fedora e.t.c.
• $uname
• O/P- Linux
• Uname -r :
• The Uname with -r is used to display the kernel version of operating
system.

54
host
• hostname :
• The hostname is used to display the host name or server name.
• $hostname
• hostname -i:
• This command is used to show the host ip address.

55
find
• List all files found in the current directory and its hierarchy
• $ find ./Sarvesh
Search a file with specific name.
• $ find ./sarvesh -name file2
Search a file with pattern.
• $ find ./sarvesh -name *.txt
How to find and delete a file with confirmation.
• $ find ./sarvesh -name file2 -exec rm -i {} \;

56
Search for empty files and directories.
• $ find ./Sarvesh –empty
Search for file with entered permissions.
• $ find ./sarvesh -perm 664
Search text within multiple files.
• $ find ./ -type f -name "*.txt" -exec grep ‘good' {} \;

57
Networking commands in Unix
• fconfig – show and set IP addresses (found almost everywhere)
• ip – show and set IP addresses (in recent Linux versions)
• ping – check if remote host is reachable via ICMP ping
• netstat – show network stats and routing information

58
Other commands
• tty :
• This displays current terminal name.
• uptime :
• it displays how long server is up & running, no of users connected,
average load on the server.
• SU :
• it is used to switch from one user account to another user account.
• Example :
• $su exam2
59
du
• du command stand for disk usage which is a standard unix/linux
command, used to estimate and display the disk space used by files
on a machine. The du command also displays the files and directory
size in a recursively manner.
• Syntax: du
• -0, --null [ end each output line with NUL, not newline]
• -a, --all [write counts for all files, not just directories]

60
• -B, --block-size=SIZE [scale sizes by SIZE before printing them; e.g.,
'-BM‘ prints sizes in units of 1,048,576 bytes; see SIZE format below
-b, --bytes [equivalent to '--apparent-size --block-size=1']
-c, --total [produce a grand total]
-d, --max-depth=N
[print the total for a directory (or file, with --all) only if it is N or fewer
levels below the command line argument;--max-depth=0 is the same as
–summarize]

-k like --block-size=1K
-m like --block-size=1M
61
print sizes in human readable format (e.g., 1K 234M 2G)
• -h, --human-readable

list inode usage information instead of block usage


--inodes
count sizes many times if hard linked
-l, --count-links

62
Displays a list of directories and how much space they consume, sorted
from the largest to the smallest.
• du | sort –nr

63
Unix / Linux - Shell Input/Output
Redirections
• Redirection is a feature in Linux such that when executing a
command, you can change the standard input/output devices. The
basic workflow of any Linux command is that it takes an input and
give an output.
• The standard input (stdin) device is the keyboard.
• The standard output (stdout) device is the screen.
• With redirection, the above standard input/output

64
Unix / Linux - Shell Input/Output
Redirections
• The output from a command normally intended for standard output
can be easily diverted to a file instead. This capability is known as
output redirection.
• If the notation > file is appended to any command that normally
writes its output to standard output, the output of that command will
be written to file instead of your terminal.

• By using some special notations we can redirect the output of many


commands to files, devices, and even to the input of other
commands.
65
Input
• 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.
• Here the shell interprets the << operator as an instruction to read
input until it finds a line containing the specified delimiter.
• The general form for a here document is −
• command << delimiter
• document
• delimiter

66
Standard Output
• Most command line programs that display their results do so by
sending their results to a facility called standard output. By default,
standard output directs its contents to the display. To redirect
standard output to a file, the ">" character is used like this:

67
Standard Output
• ls > file_list.txt
• ls >> file_list.txt
• $ who > users
• $ cat users
• ls *.txt | cat > txtFile

68
Standard Input
• Many commands can accept input from a facility called standard
input. By default, standard input gets its contents from the keyboard,
but like standard output, it can be redirected. To redirect standard
input from a file instead of the keyboard, the "<" character is used like
this:

• sort < file_list.txt


• sort < file_list.txt > sorted_file_list.txt

69
Input redirection
• Input redirection
• The '<' symbol is used for input(STDIN) redirection

70
• cat < file.txt ['file.txt' as input and displayed its content.]
• tr ‘day’ ‘DAY’ <file.text

71
EOF
• The here document (sometimes also called here-is-document) is a
way in which you can enter input until a certain
sequence(usually EOF) is typed. The EOF (End Of File) can be typed or
can be called by pressing (ctrl + d) keys.
• Any word can be used in place of 'EOF' like we have used 'last'.
• Syntax:
• cat <<EOF> <fileName>
• cat <<EOF> file.txt
• cat <<last> file.txt

72
Command Meaning

command > file redirect standard output to a file

command >> file append standard output to a file

command < file redirect standard input from a file

pipe the output of command1 to the input of


command1 | command2 command2

cat file1 file2 > file0 concatenate file1 and file2 to file0

sort sort data

who list users currently logged in

73
alias
• alias dirA="echo ..$PWD"
• alias pp="ls -i"

74
Shell name
• echo "$SHELL"
or
• ps -p $$
or
• echo $0
• To check the version-
• bash --version
• To check whether shell is installed or not
• cat /etc/shells

75
76

You might also like