0% found this document useful (0 votes)
193 views

Linux Unit 1 & 2

Uploaded by

Hari Murali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
193 views

Linux Unit 1 & 2

Uploaded by

Hari Murali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 81
— SYLLABUS Linux Administration Unit-1 Overview of Linux : What is Linux, Linux’s root in Unix, Comm, advantage of Linux, Overview of Unix and Linux architectures 7c" hardware requirements for Linux, Linux standard directories. Comma ea directories ed, Is; ep, rm, mkdir, rmdir, pwd, file, more, less, Creating and Fo Ble using cat, file comparisons. ‘owing fi, Unie 2 Essential Linux commands: Processes in Linux, process fundamentals, processes with pipes, redirecting inpu/output, Background processing, manag" processes, process scheduling ~ (at, batch), nohup command, kill, ps, who, fa touch, file, fle processing commands - we, cut, paste etc Mathematica ena," eee ce ing files with vi ctor. al Units e Shell programming - Basics of shell programming, various types of shell available ‘comparisons between various shells, shell programming in bash. Conditional g statements, case statement, parameter passing and arguments, Shel! variables, , ables shell keywords, Creating Shell programs for automating system, ormance - file security & Permissions, ion with uname, host name, disk packages with rpm command OVERVIEW OF LINUX ‘An operating system acts as an intermediary between the user ofa computer and computer hardware. The purpose of an operating system provide an environment in which a user can execute programs in a cient manner. So, to work on your computer, you is to convenient and effi need an Operating System (OS). Linux is an operating system or a kernel which germinated as an idea in the mind of young and bright Linus Torvalds when he was a computer science student. He used to work on the UNIX OS (proprietary software) and thought that it needed improvements. However, when his suggestions were rejected by the designers of UNIX, he thought of launching an OS which will be receptive to changes, modifications suggested by its users. So Linus devised a Kernel named Linux in 1991. Though he would need programs like File Manager, Document Editors, Audio -Video programs to run on it. So around 1991, a working Linux operating system with some applications was officially launched, and this was the start of one of the most loved and open- source OS options available today. Linux is a free open source operating system (OS) based on UNIX that was created in 1991 by Linus Torvalds. Users can modify and create variations of the source code, known as distributions, for iters and other devices. The most common use is as a server, but r need an. antivirus, there is a globa| | at ways to enhanc: oming a householé onment. You may Overview of Linux de, Fe . lone of UNIX. So learning one same. Since Linux learning another. Common Linux Features ie Following are some of the important features of Linux Operating ts System. > Portable— Portability means software can works on different types q of hardware in same way. Linux kernel and application programs support their installation on any kind of hardware platform. > Open Source — Linux source code is freely available. Multiple teams work in collaboration to enhance the capability of Linux operating system and it is continuously evolving. » Multi-User — Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time. > Multiprogramming - Linux is a multiprogramming system means multiple applications can run at same time. » Hierarchical File System - Linux provides a standard file structure in which system files/ user files are arranged. > Shell —Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used. to do various types of operations, call application programs. etc. > Security — Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data. > Graphical User Interface- Linux is command line based OS but it can be converted to GUI based by installing packages. > Support’s customized Keyboard-As it is used worldwide, hence Supports different languages keyboards. > Application support-It has its own software repository from where users can download and install many applications. Linux can also run Windows applications if needed. OER Of 11 > Security:- Linux is one of the most secure operating systems. File ownership and permissions make Linux more secure, > Networking;- Linux provides a strong support for network functionality; client and server systems can be easily set up on any computer running Linux. It can perform tasks like network backup faster than other operating systems. > Multitasking:- Linux is a multitasking operating system. It can handle many things at the same time. > Fast and easy installation:~ Linux distributions come with user- friendly installation. > Better use of hard disk: even when the hard disk is almost full. > Wider Choice:- There are a large number of Linux distributions which gives you a wider choice. Each organization develops and support different distribution. You can pick the one you like best; “the core functions are the same. Linux uses its resources well enough The most popular Linux distributions are:Red Hat, Ubuntu, Linux Mint, Arch Linux, Deepin, Fedora, Debian, openSUSE, Debian, CentOS, Scientific Linux etc. Overview of Unix and Linux architectures (Linux System Organization) The following illustration shows the architecture of a Linux system — erie of Lin, Linux files system Each physical drive can be divided into several partitions. A partition is a container for information and can span an entire hard drive if desired. Each partition can contain one file system. A file system is a logical collection of files on a partition or disk. It is defined as the methods and data structures that an operating system uses to keep track of files on a disk or partition; that is, the way the files are organized on the disk. The word is also used to refer to a partition or disk that is used to store the files or the type of the file system. When a partition or disk is formatted, the sectors in the hard disk are first divided into small groups. This group of sectors is called as blocks. The size of each block is 512 bytes. All the blocks belonging to the file system are logically divided into four parts. + Boot Block Super Block + Inode Table + Data Block PERE 1. Boot Block A Boot block located in the first few Sectors of a file system. The ‘b contains the initial bootstrap Program used to load the em. Typically, the first sector contains a boot strap program ars r bootstrap program from the next few sectors, and 0 08 0f LN, SS | 15 Pointers to the blocks storing file’s contents e File protection flags Some other metadata about file. 4, Data Block Data blocks start at the end of the inode list and contain the actual file contents. Data blocks contain several types of files. It contains users files, special files related to user data-regular files, directory files, symbolic link files, character special files, block special files etc. An allocated block can belong to only one file in the file system. This block cannot be used for storing any other file’s contents unless the file to which it originally belonged is deleted. Some Linux-supported File Systems » Ext- stands for “Extended file system”, and was the first created specifically for Linux. It’s had four major revisions. “Ext” is the first version of the file system, introduced in 1992. It was a major upgrade from the Minix file system used at the time, but lacks important features. Many Linux distributions no longer support Ext. Ext2, Ext3, Ext4:- These file systems are robust. ext2 was the ault file system under the 2.2 kernel. ext3 is simply the enhanced lesystem with a journaling feature. ext3 is the default file for RHEL 3 and 4 and offers the best performance (in terms and CPU usage) combined with data security of the file Supported under Linux due to its journaling feature. ext4 igned for high scalability and provides near native even when the file system spans multiple storage Pe ‘ Oh. | ee a & Q9, 2 Directory Fite ‘stat When you ereate a directory in Linux, a directory file is Map, utomatically created by the operating system. The directory file has the same name as the directory and contains information about the files aa stored in the dire ‘ory. A user cannot modify a directory file. However ‘ i when a file or subdirectory is added to the home directory, the directory agit file is modified automatically by the Linux operating system, home 3. Special Files/ Device Files “ation Most of the system files in Linux are special files. Special files are usually associated with input/output devices. Special files are stored in S standard Linux directories such as /dev and /etc. A user cannot modify special files. On Linux systems there are two flavours of special files ayy {OF €4Ch device, character special files and block special files, ‘mall When a character special file is used for device Input/Output(1/0), data is transferred one character at a time. This type of access is called raw device access. When a block special file is used for device Input! Output(/O), data is transferred in large fixed-size blocks. This type of hey access is called block device access. Pipes Linux allows you to link commands together using a pipe. The pipe acts a temporary file which only exists to hold data from one command until it is read by another, A Linux pipe provides a one-way flow of data. The output or result of the first command sequence is used as the input to the second command sequence. To make a pipe, put a vertical bar (|) on the command line between two commands. 5. Socket file A socket file is used to pass information between applications for communication purpose. Socket is used in a client-server, application __ framework. —$—$——— LE Ader ton 6, Symbolic Link Symbolic link is used for referencing some other file of 1 h es to other files. There are two Wee © file system, These are linked fil of link files available in Linux: soft link and hard link, Soft link is an actual link to the original file, whereas a hard link a mirror copy of the original file. If you delete the original file, the a link has no value, because it points to a non-existent file. But the hard Link can still has the data of the original file, because hard link acts as i mirror copy of the original file. Linux standard Directories There is a solid difference between the way the user sees the Linux file system and the way the kernel actually stores the files. To the “user, the file system appears as a hierarchical arrangement of directories that contain files and other directories i.e., sub directories. Directories and files are identified by their names. The Linux file system resembles an upside down tree. And this hierarchy starts from a single directory called ‘root’, which is represented by a “/” i.e. forward slash. Branching from root directory there are several standard sub directories. A Linux file system is a collection of files and directories that has the following properties: Ithas a root directory (/) that contains other files and directories. Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode, Byconvention, the root directory has an inode number of 2, inode numbers Oand 1 are not used, File inode numbers can be se by specifying the -i option to ls command. _ @ It is self-contained, There are no dependencies between ont filesystem and another. Overview of Linux Root directory is top level directory in the file system hierarchy and this directory contains all other directories and their subdirectories. It must contain all of the filesrequired to boot the Linux system before other file systems are mounted. It must include all of the required executable and libraries Tequired to boot the remaining file systems. After the system is booted, all other file Systems are mounted on standard, well-defined mount points as subdirectories of the root file system. The root directory also contains a file called as Linux which is Linux kernel itself. /bin Tt contains essential binary files, such as commands that are needed by both the system administrator and normal users. Usually also contains the shells, such as Bash. /boot Contains the static boot loader and kernel executable and configuration files Tequired to boot a Linux computer, /dev This directory contains the device files for every hardware device attached to the system. These are not device drivers, rather they are files that Tepresent each device on the computer and facilitate access to those devices. These include terminal devices (tty*), floppy disks (fd*), hard disks (hd* or sd*), RAM (ram*), and CD-ROM (cd*). Users can access these devices directly through these device files; however. > Some applications hide the actual device names to end users, i :. ¥F )—— na in, ete It contains administrative configuration fi directories i,c. other additional commands i) ng i ioral : which ,,,| related to system administration & maintenance te /home Home directory storage for user files. Each —~ 7 7 User has) subdirectory in /home A — Aib Contains shared library files and sometimes Other La related files that are required to boot the system, el. /media | Mount points for removable media. Provides ast location for auto mounting devices (removable particular). If the medium has a volume name, t] is typically used as the mount point. For examp! drive with a volume name of myusb would be m /media/myusb. tandarg | Media jn hat name le, a Usp lounted on /mnt A temporary mount point for regular file Systems that | can be used while the administrator is Tepairing or wo king on a file system. /opt Optional files such as vendor Supplied application programs should be located here. Typically contains extra and third party software. /root It is the home directory for the root user. The home directory for root does not reside beneath /home for security reasons. System binary files. These are executables used for system administration. /sbin is similar to /bin, but it contains applications that only the super user will need. Contains administrative commands and daemon processes Used by the operating system and many programs to store | temporary files. Users may also store files her temporarily. Note that files stored here may be deleted at y time without prior notice. oot ust wat prt [ruse Overview of Linux 21 Contains user documentation, games, graphical files, libraries, and a variety of other commands and files that are not needed during the boot process. ie, programs, libraries, documentation etc. for all user-related programs. /var Variable data files are stored here. This can include things like log files, MySQL, and other database files, web server data files, email inboxes, and much more. In particular, this is where you would place files that you share as an FTP server (/var/ftp) or a web server (/var/www). It also contains all system log files (/var/log) and spool files in / var/spool (such as mail, cups, and news). _ /proc Vie Contains information about system resources. It contains information about your computer, such as information about your CPU and the kernel your Linux system is running. Contains data for servers. If you are running a web server from your Linux box, your HTML files for your sites would go into /srv/http (or /srv/www). If you were running an FTP server, your files would go into /srv/ftp. isys Hardware /sys is another virtual directory like /proc and /dey and also contains information from devices connected to your computer. Following are the salient features of the Linux file system: ¢ Ithas a hierarchical file structure. e Files can grow dynamically Files have access permissions e All devices are implemented as files. requirements for Linux You can get a Linux distribution that runs on hand-held devices or an old PC in your closet with as little as 24MB of RAM and a 486 7 22 Lin Lines Admin wt processor. To have a good desktop PC experience with Tike tiny ests) you should consider what you want to be able to do with rie °™*ve a inux you are choosing your computer. Whey » Processor — A 400 MHz Pentium processor is the Tinimom Ext! GUL installation. For most applications, a 32-bit Procesggg. ta 7 (486). However, if you want to set up the system to do san ng oy you need a 64-bit processor (x86_64). alization ygHiBSe > RAM — Needs at least 1GB of RAM, but at least 2G cost would be much better. &T3Gq a > Disk space — Needs at least 10GB of disk sy = * Pace for an ay, desktop installation, although installations ci a ~ 1 on which packages you choose to install) from s00Me nt sper! minimal server with no GUI install) to 7GB (to install att ae a Gynt from the installation media). Consider the amount of data — Aes to store. While documents can consume Very little space ae can consume massive amounts of space. ee > DVD or CD drive — You need to be able to boot up the installation process from a DVD, CD, or USB drive. If you can’t boot from a DVD or CD, there are ways to start the installation from a hard | disk or USB drive. After the installation process is Started, more software can sometimes be retrieved from different locations (over the network or from hard disk, for example). | Network card — You need a wired or wireless networking hardware to be able to add more software or get software updates. Special hardware features — Some Linux features Tequire special hardware features. For example, to use as a virtualization host using KVM, the computer must have a processor that supports virtualization. These include AMD-V or Intel-VT chips. an Page in Linux The manual (man) pages provide detailed descriptions and oe the commands. You can use the man command to display the ™! Overview of Linux age entry that explains a given command. The syntax of the man command is as follows. man Example: man Is This command displays the man page /s command. Is is used for listing. Commands for files and directories ed: To change directory - change the current working directory to a specific directory. Syntax: cd [Options] [Directory] change to your home directory 1 ed / change to root directory / cd.. | change to parent directory ! cd - change to previous directory where you working earlier The directory in which you find yourself when you first login is called your home directory. You will be doing much of your work in your home directory and subdirectories that you'll be creating to organize your files. Eg 1:- You can go in your home directory anytime using the following command Here ~ indicates the home directory. 2 Lin Ay Eg 2:- Suppose you have to go in any other user’s home directory the following command ic ed ~username Eg 3:- To move inside a directory from a directory 1 ed dirl/dir2/dir3 | Eg 4:- To navigate to a directory with white spaces, Specify diver, Mectory name in double quotes or single quotes. ed “dirname” [salmiya@lotathosts=]$ cd dirl/dir2/dir3 [salmiya@localhost-dir3]$ cd .. PEE VUP AE akte tener ar Faas MEMES lWere- tuts ame tars BO] ty [salmiya@lo¢alhost bin]$ cd ~ IEE VOPR clea Wee =]$ ed / ES UMIBR (ch Mere Witt g ve R ac: /home/salmiya ! [salmiya@locathost.~]§ {| Is Is command is used to list the content of the specified directory ie. directory and files ina directory. Is [option] [directory] "I Option | Meaning -a List all files including hidden files starting with ‘.” eu=d List directory List with long format | List in reverse order —— Linux Administration 26 ——_ Example : cp test.txt sample.txt Copy the file “test.txt” to the file “sample.txt” in the current working directory. This command will create the file “sample” if it doesn’t exist, It will normally overwrite it without warning if it exists. > To copy multiple files using the cp command, pass the names of files followed by the destination directory. To copy entire directory structures from one place to another use the -R option to perform a recursive copy. cp copies all files of th source directory to the destination directory, creating any fil E directories needed. pee a In the above command, i ry x: , if the Dest_dire _ a : D ectory doesn’t exi ae = copies content of Sre_directory recursively ae ee Dest_dire iy exists then copy of Src_directory becom ce ie st ecomes sub-directory > If you want to be pr Reon prompted before over writing a file, use the -i > a / (or yes) ) then sample. txt will be overwritten with acopy } that are bei . and folders thar yon the -Y Option tothe ep. This tare being copied to standard output. Se 77 Overview of Linu: NTC CE g ‘ Cee aee eT Usb | [salmiya@locathost ~]§ [salmiya@localhost ~]$ cp -v test. txt sample.txt. dirl ‘test. txt’ -> ‘dirl/test. txt’ CS Em UU Cree f Occ e) salmiya@localhost ~]$ cp filel.txt -iv sample. txt sReMrT Cast any Re coeeemet Csta | Umiya@localhost ~]$ || rm The rm command is used to remove files or directory. To remove a file, you must have write permission for the directory that contains 1 the file. rm [options] Options} Meaning | “i Prompt before every removal -l Prompt once before removing more than three files, or when removing recursively -r, -R Remove directories and their contents recursively -d Remove empty directories -f Remove write-protected file, never prompt before removing -v Explain what is being done(print the name of each file before removing it) Eg-1: Remove the file test.txt, If the file is write-protected, you will be prompted to confirm that you really wanto delete it: “mm test.txt Eg-9:Same as the above command, but you will never be prompted; 1 tm can delete the files, it will: 1, Overview of Linux ———_____ - 29 ya@locathost ~]§ rm eaaas ts set: Noss Ca Se ere UES iya@locathost -]$ rm -rv dirt Peierirraca] dir3! ved directory: ‘dirl/dir2’ ved ‘dirl/test.txt’ eC ris Vero a Chesca eerie! mkdir The mkdir command is used to create a new directory. This command can create multiple directories at once and also set permissions when creating the directory. mkdir [option] -m Set permission mode | -? Create parent directories as necessary. When this option is | specified, no error is reported if a directory already exists. oY Print a message for each created directory | Eg-1: Creates a new directory called ‘mydirectory’ whose parent is the current directory. Eg-2: Create the directory ‘mydirectory’, and set its permissions such that all users may read, write, and execute the contents. Eg-4: To create several subdirectories at one time, Use =P option tg intermediate directories if not exists. ys mkdir -v mydirectory PVT i [EST eats eee Menace] ya@Localh rf 5 Yaelocathost ~]§ mkdir -v dif dir2 Sehnert meric casi rae Inkdir: created directory ‘dir2’ CNRS cis a Beatie aes eer eerep ures rae Ry ee Seyi tacig) created directory ‘ Serie a tac te nee ect Ade pert Ursa) rmdir The rmdir command is used to remove the directory. The should be empty before removing it. rmdir [options] Options | Meaning -V Print a message for every directory processed, explain whatis being done -p Each of the directory argument is treated as a pathname which all components will be temoved, if they are 4 empty, starting from the last component. Eg-1: To delete the directory te rmdir test Eg-2: To delete nested empty directori eats tmdir -p first/second/third Overview of Linux —= . Eg-3:Remove the directories dirl, dir2, and dir3, if they are empty. If any are not empty, an error message will be printed for that directory, and the others will be removed. rmdir dirl dir2 dir3 [salmiya@localhost ~]$ rmdir -v mydirectory rmdir: removing directory, ‘mydirectory’ eeGreote es es ya@localhost ~]$ rmdir -pv first/second/third removing directory, ‘first/second/third’ y removing directory, ‘first/second’ ee tase Aen eae [salmiya@loc@ host pwd The pwd command displays the present working directory or current directory. pwd [option] Options | Meaning =| L Display the content as absolute name (Print symbolic path) =F Print fully resolved name for the current directory (Print actual path) [salmiya@locathost ~]$ cd /bin erica sd mr Ure a ear) Pri [salmiya@locathost bin]$ localhost bin]$ pwd -L NEOs e SUES [salmiya@localhost bin]$ pwd -P usr/bin ECC a ny 32 file how to view or work with a file. The file name along with the file be printed to standard output. file [options] Meaning To show just the file type To view the mime type ofa file rather than the format human, File and file type are separated by : But we can ch: Separator using -F option Used for special files. To view compressed files without decompressing Overview of Pon Eg 6:- To display special files Pe (, fe file -s /dev/sda ‘tenn Z F pe, Eg 7 To display file types of multiple files Ye, [7 file file1 file? file3 (NEOs es keeche ey ees lsample.txt: ASCII text wa eee leet KS {salmiya@localhost: ~]$ file’ -b sample. txt ASCII text [salmiya@locathost ~]$ [salmiya@localhost ~]$: filer ange Ce Chae tad la\g a Peas directory Pictures: directory sample. txt: ASCII text icin seme Wa sone <3 c almiya@localhost. =]$) file>: Paulas = Dee ase 119 un 1a cee HUD EC Ye Cir ae ie cs more If the information to be displayed on the screen is very long, it scrolls up on the screen fastly. So the user cannot be able to read it. The more , ©ommand is used to display the output page by page (without scrolling Up on the screen fastly). While viewing the file use the following controls: Enter key : To scroll down line by line. Space barorfkey : To go to the next page bkey ~ : To go to back one page To quit displaying —— Linux Administra, —_—_—_—_— : = ee The syntax is as follows: Prompt the San ; “q’ to quit.]” and will display “[Press ‘h’ foegemetouctions instead of ringing the bell when an illegal keygisipressed: Squeeze multiple blank lines into one. Omits the underlines. mmand has the same syntax and functions of more.ie, used of text file one Page per time (one screen). It has faster file is large, it don’t access complete file, but access i r example, if it’s a large file and you are reading it usin the complete file will be loaded to main memory, bu! toad entire file, but load it part by part, which makes _ less XN 35, Overview of Linux causes less to exit if entire file can be displayed on first screen Squeeze multiple blank lines into one. Omits the underlines. Suppress line number Creating and viewing files using cat The cat command is used to display the content of text file and to combine several files to one file. It is also use to create a file. The cat command (short for “concatenate “) is one of the most frequently used command in Linux. The cat command allows us to create single or multiple files, view content of file, concatenate files and redirect output in terminal or files. The cat command display files content to a screen. The cat command can read and write data from standard input and output devices, It has three main functions related to manipulating text files: creating them, displaying them, and combining them. It is also used to copy text files into a new document. cat [options] terminal. Once you’re done, just press Ctrl+d 1 > cat To create a new file, use: cat > [name-of-new-file] When run, the command requires you to « To copy the contents of one file to cat [filename-whose-contents-is filename] To display contents of multiple filles: voll . cat filename! filename2 Filename. 7 > be Ce To append the contents of one file to another, yo greater than ‘>>’ symbol with the cat command, _ cat filenamel >> filename2 Here, the content of filename] is added at the end of filena To display contents of all txt files, use the following co mu cat *. txt { To display the contents of a file with line number, use the command, cat -n filename ‘= To create a new file: e568 0 Overview of a = 37 Eg 3:- To copy the contents of one file to another file eat sample.txt > samplecopy.txt E | Eg 4:- To append the contents of one file to another [eiteamptee este er Ser Pirarroe iets pees eta) i Weer ries ata ass Pargrnos ier Oi ens Berta Be atu Be Breese se Ga rarer cis) Peer itr aero! pees pees preemies’ ere riaes ey BUH OPTEP ee ee Pe atr Lens tae raha s ame eriprn tae Pataca PPT Bs File Comparisons Commands The file comparison command helps us to compare the files and fi the similarities and differences between these files. The different file comparison. commands used in Linux and uniq 1. cmp: are two files character by character are cmp, comm, difl This command is used to comp: emp [options] p command is used to compare the two files byte by byte and he find out whether the two files are identical or not. When cmp 1 parison between two files, it reports the location of the first mismatch the screen if difference is found and display age and simply ot if the files compared are identical. It also displays line no me! -i [bytes-to-be-skipped] from both the files and then it compares the files. SKIP1:SKIP2 -l Print byte position and differing bytes. 4 Suppress all normal output, only. Limit the number of b compare. “s -n [no. of bytes] If the files are not identical the command will display the fi byte and line number If the files are identical, it displays no mes you will see something like this on your screen: $ /*indicating that the files are identical*/ skips first 10 bytes from both files and then comp in cases like these (Where you use -i to skip bytes),! comparison begins is treated as byte number zero. —_————— oo 2 Overview of Linu q Here 10 bytes skipped from first file and 15 bytes skipped from second file and the compare them. Eg 4:- cmp -I filel file2 Ifthe files are different this command displays the position of differing bytes along with the differing bytes in both file. The first column in the . output represents the position (byte number) of differing bytes. The second column represents the byte value of the differing byte in the first file, while the third column represents the byte value of the differing byte in the second file. Eg 5:- emp -s filel file2 This allows you to suppress the output normally produced by cmp command ie it compares two files without writing any messages. This gives an exit value of 0 if the files are identical, a value of 1 if different, or a value of 2 if an error message occurs. Eg 6:- This command compares first 50 bytes. Sant armen Seer) oy seo | iat | wo a 2. diff diff stands for difference. This command is use . in the files by comparing the files line by line. I pees le to make it identical of instructions for how to change one fi file. The syntax is: Ignore case differences in file contents, consi lower case letters equivalent 5 Ignore changes in the amount of white space or tabs) Ignore ail white space. -q Prompt when two files are differ S$ Report when two files are the same. The important thing to remember is that diffuses certain special s od instructions that are required to make two files identical. It tells: ions on how to change the first file to make it match the seco mse, or d for delete), and to the second file, | > Pe 4 Overview of Linux The three dashes (“- - -”) merely separate the lines of file1 and file2. And also Lines preceded by a < are lines from the first file; Lines preceded by > are lines from the second file. Example: we have two files with names file/ and file2 containing the following data. Then applying diff command without any option we get the following output: Banana CEG eee) ‘cond file line number 5. As a ake both the files identical, Change the line number 2 in the nge’ with line number 2 of fi/e2 ie, ‘Banana’. Then add rr) ON OC UC more aC Pag Era rey Estee uraeoee | Here above output 3d2 means delete line 3rd of file/ i.e. “Grapes” that both the files syne up at line 2: Linux system offers two different ways to view the diffcommand out i.e. context mode and unified mode. > Context Mode (-c) : To view differences in context mode, use the option Example: We have two files file/ and file. cg (ESOS tre sea Ps Tam ett) aed cc) PU C Uae e Crmeron sacs U CT? crit 2019-10-08 20:42; 04.310680050 +0530 AAs 2019-10-08 20:42:37.436490383 +0530 Cerny ee cor SUT y ao” = = 43 ‘The first file is indicated by ***, and the second file is indicated by —. ‘The first two lines of this output show us information about file! and file2. jists the file name, modification date, and modification time of each of Ith Cope eemeee” is just a separator. our files, one per line. The line The next line has three asterisks (“***”) followed by a line range from the first file (in this case lines 1 through 4, separated by a comma). Then four asterisks (<+***”).After that it shows the contents of the first file with the following indicators: 1, Ifthe line needs to be unchanged, it is prefixed by two spaces. 2. Ifthe line needs to be changed, it is prefixed by a symbol and a space. The symbol means are as follows: It indicates a line in the second file that needs to be added to the first file to make them identical. Tt indicates a line in the first file that needs to be deleted econd file. than one section that needs to change, diff will show ter the other. Lines from the first file will still be lines from the second file with “—”. view differences in unified mode, use the -u it shows the information in concise forn ‘context mode but it doesn’t display any we Linus Administra LE ee Example EGS res errr Le RLU Sse meer eT me etd & cRt PLPC PCE Bp CS eee) i PSUS CE i RUS o CE EMC er) salmiya@locathost: ~}§ | The output is similar to “unified” into one set above, but as you can see, the differences are. The first file is indicated by +++. The first two lines of this output file2. It lists the file » and the second file is indicated by show us information about filel and name, modification date. » and modification time of each of our files, one per line. After that the next line has two at si from the first file (in our case Prefixed by — and then space the second file prefixed by + file content in Output tells us and which lines needs to added or deleted (indicated by symbols) in the file 1 to make identical to file 2, gn @ followed by a line range lines | through 4, Separated by a comma) and then again followed by and at the end two at Sign @. Followed by the which line remain unchanged a line range from 3. comm i ei Used to Compare two sorted files line by line out : ut: the lines that are common, plus the lines that dard and write to stam are unique Overview of Linux 45 comm [options] With no options, it produces three-column output. Column one contains lines unique to File1, column two contains lines unique to File2, and column three contains lines common to both files. comm command only works right if you are comparing two files which are already sorted. Option | Meaning “1 | suppress column 1 (lines unique to FILE1) 2 suppress column 2 (lines unique to FILE2) | = suppress column 3 (lines that appear in both files) | Vfilel file2 This command suppress column 1 , ie, lines unique to filel eres aS Bree ursesr as antic PCs i as elas oc Ge ros Orin th the help of uniq command you can form a sorted list in which will occur only once. ie,the uniq command reports or filters DS n | Meaning Displays only the duplicate lines Displays only unique lines Normally, comparisons are case-sensitive. This option performs case-insensitive comparisons instead Displays line by eliminating duplicate lines and prefix lines: with a number representing how many times they occurred, To sore the output of wiq command; you should specify the destinati filename as shown below: uniq [salmiyaglocathost. ~]§ cat, titel OST OCU eoraC msi eae SUN Ce aa rare eters Perrier rere Para pe) iD ae Hangoe OLS r Cems iene SUC TUS ret C iran rest 2 Apple aoe ach eves trent sey] “Ht —= Linux Administ, | g 1:- Listing all ile and directories an ive input to more com: direc d give it asi :) yall filesand 0 i eg 1:- Listing all fi ae = ess: i Ss. = s output The more command take! : | this command is that the output of Is -/ is displayed one screen at a tim, j sa | The pipe act as a container which take output of Is - and giving it to mor, as input. This command does not use adisk to connect standard output of || _Jto standard input of more because pipe 1s implemented in the main memor | | | y 1 of ds -/as its input The net effect yf Use sortand unig command to sorta file and print unique values. — = ~ 7 | sort filef | uniq be SEs see a ee ee This will sort the given file and print the unique values only. [salmiya@localhost ~}$ cat filel | | [eS are Urea tee command The fee comm: S ommand reads the standard Input and writes it to both th oth the standard our : output god one or more files. It asicall Program So that it can 4@ both displ on. the tasks simulta : d and saved in a fj , eae ineously, copies the result into th a file. It does bot! isplays the result ae the specified files and alse Syntax: Command] | Cor mmand2| ...| tee < es filename> oe a pie comes fa command line contains the output redirection symbol (~) followed pyafilename, the standard output from the command will go to the specified file instead of to the terminal. If the file didn’t exist before the command wwasinvoked, then the file is automatically created. Ifthe file did exist before the command was invoked, then the file will be overwritten; the command's ouput will completely replace the. previous contents of the file. If you want to append to a file instead of overw ing, you can use the output redirection append symbol (>>), This will also create the file if it didn’t already exist. psi Example 1: cat sample This command will display the content of sample file. To redirect the output of the cat command, use the following command, cat sample > test This cat command displayed nothing, as the output of the command is redirected to a file. If we check the contents of file test, it will contain the same text as sample (the output of the cat command). Example 2: E Is41> filelist This command stores the result of Is —1 to the file filelist, VERE Cee trae eer le his is a file named sample Bhowing output redirection [salmiya@localhost ~]$ [salmiya@localhost ~]$ cat sample > test [salmiya@localhost ~]$ Salmiya@localhost ~]$ cat test Pee eer ee RM UC er Showing output redirection [salmiya@localhost ~]$ USPGAAmole eee nthe | 08 OF tee th) Usa Amol Pati Invitational on Thy Th pieraen oe pat Severe | i Dechambea Anne return mbH the, ted ard ne P72 le ‘nate Prajnesh gore ee ince Adnan 58 Input Redirection < ve can send output anywiere Wie” SE ay orice «from places other than the Keyboard, ve can also get inpul fi is oe symbol ( < ) for input redirection. Syntax is as 2 Linux follows: Command-options-and-arguments < input-file Example: aus ai mand sends the file.txt file to the more command. This com sort < file] Here, sort command is used for sorting the content. Here the input to sort command is file] ]$ cat filel (EEO cre Notes [ESUPSAC Teac a ae Paco Ear WSS ae) 3. Error Redirection The stden i see é fees stream can be redirected in a similar fashion as sédin of a eon s poe symbol for redirecting stderr. The same “>” with the number 2 attached in ft i d but in front of it. We use “2>” for stderr redirection to tell the shell that we wa t i a messages instead of stdout. The Syntax is: “ae Command-options-and-arguments 2> output-file Bere Line Admini a 62 Options for listing the s _ forremoving a submitted job an vse arg command (oF at) 10 display all the at comme, veduled (pending. jobs) or. currently, running. Syntax js: ubmitted jobs atq: You jobs that a aq atrm:- You can use_airm command (Or af -d), to delete a particuly job. Syntax is: atrm EOE lat> echo “LUNCH BREAK” hao jjob 7 at Sat Oct 12 SOREL HL ay ey [eure cere uth enue ste aes rere ON ca lat> sort fitel ca Sn scrataar CeCe HL eC) [salmiya@localhost ~]$ enttcatrs irr sera cy Eeaaar ere eC eu cl ic Pee CYA] at] a4 rs a aoe ost Sliema batch:- \ This co! is mmand is used to execute the specified commands when the system load ad is light (when CPU becomes nearly free). General format i batch Ad Any job scheduled with batch also goes to the at queue, ce as i Re runiya@localhost ~]§ ps 2 Re 1 Ay sa) Laas TLL 7 pts/0 CRC RL ars iya@localhost ~]§ Since Linux is a multiuser operating system, several users may work onthis system. This command is used to display the users who are logged on the system currently. General format is: e who [options] _|_ Meaning Aa % The time of last system boot | lists all available output for each user on your system, Display dead processes Print line of column headings Print system login processes Print all login names and number of users logged on Print only name, line, and time (default) Print the last time the system clock was changed, if the information is available. The first column of the output represents the user names. The second Column represents the corresponding terminal names and the remaining Column represents the time at which the users are logged on. Who am i:- This command tells you who you are. 66 2019-1 salmiya Pit) Heer za ks Pour Nee eae [VG cash hema YF Ue satmiya pts/O sl eerste Neer ae ed find The find command helps in locating files which meet the cars| criteria. This command recursively examines. the specified directory to look for files matching some file attributes, and then takes some. action on those files. General format is: find It recursively examines all files in the directories specified in (file attributes) Finally, it takes the specified on those selected files. The may be as follows: Selection Criteria | Meaning 3 —hame | Selects the file specified in . =user | Selects file owned by . type d Selects directories, -size +n or —y Selects files that are greater than/ less than “n” locks. Generally one block is 512 bytes Selects files that have been modified on exactly 'ys/ more than n days, ae files that have been modified on exactly 0 lutes/ more than n minutes/ less than n minutes. cee files that have been accessed on exactly 2 more than n days/ less than n days. —intime n or +n or —y a ee smmin n or +n or —n eee | -atime n or +n or —, (eee —— amin n or +n or —n -empt "Ds true if’ and is either @ file is empty (contains nothing) | & regular file or a directory. Wor ied ne Vorth | Jann HCP rocony (th \ | | wit o at jn Here. f Med an an nas ever ot RE ee ee eee oo gxamples: To sort the content of the file use: sort file in = 2 To sort the content in reverse order 7 sort -r filet a Fs To store the output to a file use : ge sort —o sortfile filel al This command not displays anything, but stores the result in sortfile. 4, To sort the file with numeric data: Ez sort —n number.txt [salmiyaglocathost ~}5 (eed (Sopot : eT enurbarere reas Assam feats) faa Terrie eee (salmiya@Locathost eee Tora reat) (eluEe Assam [salmiya@locathost NEC Lea aera Taree ee rar aes aCe Tes Peau Le (opatons= [a ean Displays the number splays the number of Words E Displays the number of bytes in tie a - —_ |" Displays ters in the file [om | Disrnys te unter of hare Sd Ee pable of accepting input directly ftom the keyboard. By entering we without any arguments, it waits for the use, to type in the input. On terminating input (using Cirl+4), the approprs counts are displayed for the input that you supplied. of lines in the file words in the file The we command is caj Without any option, the command displays total number of lines, words, and characters. Examples: 1. we sample 2. we -I sample __ When more than file name is specified in argument then command will display four-columnar output for all individual files plus one extra a displaying total number of lines, words and characters of all the iles specified in argument, followed by keyword total. we filel file? files mple re eae renee poe see ees ates uc) atte carte Ce [salmiya@locathost ~]$ | | paste This command concatenates the contents of the specified files into a single file vertically. It is used to merge lines of files. General . format is; [pase iienanet Sao [ Options Meaning aus | -s Paste one file at a time instead of in parallel(merge in -d DELIM | Use character DELIMes delimiter instead of a tab ae ee eg Without any option paste Merges the files in parallel. The paste command writes Corresponding lines from the files with tab as a delimiter on the terminal. Mie next feet oe Match am rain TMB remaing my 18 who wee 75 nsider two files having name state and capital. state and le contains 5 names of the Indian states and capitals Jy. To merge these files use: jet us © capital fi respective paste state capital > Tomerge the files in sequential manner: c= Ts state capital 3, To use : as delimiter | paste —d “:” state capital [salmiya@localhost ~]$ cat state Kerala SPecrare Seca [salmiyaglocalhost ~]$ paste state capital eestor ears Couns Ms Dee taka rie (iateei ees a Cem cm. tc le Reeacery) Perum cus Lc) Metals cee se ee eT (Ever reese Ed (EU Ne eter et! Bhat als erala: Trivandrum CNT ee unr ee eur en Seren oreeta [Eotrtcere crt seers M; ‘thematical commands qT e a ‘te are different commands are available to perform mathematical “Mons, Ng e ‘ 2 ee Linux Administra, 76 expr This commal ' gers. It can’t handle floating inte; The arithmetic operators and thei below. oh * % rm arithmetic operations 9, ; fo) nd is used 10 perform ic, General format is point [_eprespres on | iat r corresponding functions are given Addition Subtraction Multiplication Division Remainder of divisio A white space must be used on either side of an operand. Multiplication operator should be preceded by \ symbol because in Linux * represents all files in the current directory. If we directly use * in expr, we will get error message. Examples: Eanes be [salmiya@localhost ~ [salmiya@localhost Hy eters [salmiya@locathost be Were rss localhost ~ Mere Mesa be (Basic Calculator) is a command-line utility that provides all features you expect from a simple scientific or financial calculator. It is used to perform arithmetic operations on integers as well fo on floating point numbers. | ssi tsnecomnand Ns 7 qype the arithmetic exp ¢ ression in line a . answer Will be displayed on th end ney Bias) Then € finished work, press Ctrl+d to end up fe next line, A; your py default, be performs integer division, If you requi givision, then set scale to the number of digits of preciuin ne ott f precision before the operation. [salmiya@localhost ee) [salmiya@localhost ~]$ |] factor This command is used to print the prime factors of a number. General format is: factor [number] Note: The number is given from command line or read from standard input. If the number is given through standard input it waits for another Tumber. It exits if you press Ctrl+d. Example: OPE alhost ~)$ factor 40 cena) The tilde character (~) you see in the screen shows that the file has {no text in these lines) To switch to insert mode, you press the i character ( just after starting vi. When you haye finished entering text into the file, you press the Ese and,; key to return to command mode) To save the file, you can use th :w command. After you save the file, you can quit the editor with th tommand, You clin also use’¢x dvwq to save and quit in one step Tf you want to specify any particular name for the file, you can do so by specifying it after the :w. For example, if you wanted to save the file you were working on as another filename called ‘filename2”, you would type £w filename?’ land return, Kina Multiple files can be opened with vi by supplying multiple file names at the command line. If you want to open three files (filel, file2, file3) Simultaneously, the command will be as follows: |vifilel fite2 files | Cursor Movementin yj Bde ore ft f \ arae To move the cursor’ you must the modern terminals, you can “Move the cursor with the arrow keys om your keyboard. =e — in command mode, On most of

You might also like