Shell Environment and its types

File:Gnu-bash-logo.svg

BASH has many Shell Environment variables on which its function depends. The list of environment variables which is set for current session can be listed out using env or printenv commands.

$ env
$ printenv

The Shell Environment is set, as per the configuration distributed in different files. And the list of required bash configuration files are listed below:-

  • /etc/bashrc
  • /etc/profile
  • ~/.bashrc
  • ~/.bash_profile

 

Know about Interactive and Non-Interactive Shell

When the user starts a terminal in GUI session or when user login into CLI, Interactive Shell is started. Interactive shell is where the shell session is attached to a terminal.

Non-Interactive shell is where the shell session is not attached to a terminal, such shell starts while executing shell scripts.

 

Know about Login AND Non-Login Shell

When the user starts a shell session by authenticating, login shell is started or when user login into terminal or through SSH, login shell is started. In login shell following files are sourced.

  • /etc/bashrc
  • /etc/profile
  • ~/.bashrc
  • ~/.bash_profile

When user starts a shell session from already running session, non-login shell is started. Or When terminal is started in GUI, when we run bash in running shell session, when substituting user with su, a non-login shell is started. In non-login shell following files are sourced.

  • /etc/bashrc
  • ~/.bashrc

Login or Non-Login shell can be identified easily by executing, echo $0 If the output is ‘-bash’ the it is login shell, if the output is ‘bash’ then it is non-login shell.

$ echo $0
-bash

Also certain commands work in login shell only like logout which terminates the session, works only in login shell. Executing logoutin non-login shell will give an error.

 

What is SU in Linux?

su is used to change the identity of the user without logout and login again. su command takes username as input. If the username is not passed to su, By default root user is considered.

Invoking su starts a non-login shell.

$ su
Password:
# echo $0
bash
# logout
bash: logout: not login shell: use `exit'
# exit
$

To start a login shell with su pass ‘-‘ as argument.

$ su - root
Password:
# echo $0
-bash
# logout
$

To directly execute a command as another user pass option ‘c’ to su following the command to be executed.

$ su -c "id" -
Password:
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$

What is SUDO in Linux?

su can be used to temporarily gain superuser privileges to perform certain tasks. The disadvantage is that users can do a lot more than they have gained the superuser privileges for. Users can gain superuser privileges for adding a new user and they can also remove complete /etc/ directory as well. Additionally, the users which are using su needs to know the password of root user account or other user accounts as they are trying to get the access of.

The sudo command allows a user to be permitted to run a command as root, or as another user. Unlike susudo requires users to enter their own password for authentication. So users do not need to know the passwords of accounts they are trying to run the command as.Access to other accounts via sudo is managed by a file /etc/sudoers.

In RHEL 7wheel group is allowed to use sudo to run commands as any user, including root. The users will be prompted for their own password.

If any regular user wants to use sudo, they must be the member of wheel group.

# usermod -G wheel student

Above command when executed as root, will make user student a member of wheel group. Then student can use sudo command to run any command as root, as given below.

$ touch /testfile
ERROR
$ sudo touch /testfile
$ ls /

 

 

VIM editor and its related commands

Vim Editor is command line text editor, an enhanced version of ‘vi’. To open a file in vim use below mentioned command:-

$ vim myfile

There are 2 modes of vim we use.

  1. Command mode where we run commands.
  2. Insert mode where we do editing.

How to access these Modes of VIM?

ESC    - Command mode
INSERT - Insert mode and cursor remains at same position
i      - Insert mode and cursor remains at same position
I      - Insert mode and cursor moves to beginning of line
a      - Insert mode and cursor moves one character ahead
A      - Insert mode and cursor moves to hte end of line
o      - Create newline after current line and Insert mode
O      - Create newline before current line and Insert mode

Command to Save or Quit VIM editor

To Save or Quit vim editor use

ESC:w  - Save
ESC:q  - Quit
ESC:wq - Save and Quit
ESC:x  - Save and Quit
ESC:w! - Force Save
ESC:q! - Fore Quit

There are many other commands in VIM editor to help you in editing the files with ease.

x                      - Delete character under cursor
yy                     - Copy current line
4yy                    - Copy 4 lines starting from current line
dd                     - Deletes current line
4dd                    - Deletes 4 lines starting from current line
p                      - Paste after cursor
P                      - Paste before cursor
gg                     - Go to first line
G                      - Go to last line
ESC:12                 - Go to 12th line
/<str-to-search>       - Search string in file
n                      - Go to next occurance of search result
N                      - Go to previous occurance of search result
ESC:%s/<search-str>/<replace-str>   - Replace first occurance of string in all lines.
ESC:%s/<search-str>/<replace-str>/g - Replace all occurances of string in all lines.

There is an interactive tutorial for vim editor which can be started with vimtutor command.

$ vimtutor

 

Linux File System Hierarchy

LINUX FILESYSTEM

Linux Filesystem is an inverted tree structure which consists folders and files. At the root of the filesystem is ‘/’ (forward slash). Everything under Linux is kept inside ‘/’.

When the disk is partitioned, the partitions are attached to one (or more) of the directories in the Linux filesystem. The process of attaching a partition to the directory is called ‘Mounting’.

Linux: Filesystem Hierarchy
Linux: Filesystem Hierarchy

 

FILESYSTEM HIERARCHY STANDARDS

Detailed information about the Linux Filesystem Hierarchy Standards is available in manual page – hier.

/       Root of Linux Filesystem

/bin Binary Executable files are kept here

/boot Booting related files are kept here

/dev Device files are kept here

/etc System-wide configuration files are kept here

/home Location for the home directories of regular users

/lib64 Libraries for binary executables are kept here

/mnt Temporary mount point

/opt Optional Programs are installed here

/proc Kernel pseudo filesystem

/root Home directory of super user root

/sbin System Binary Executable files are kept here

/tmp Temporary files are kept here

/usr User Filesystem

/var Variable files are kept here

HOW TO CREATE PATHNAMES OF A FOLDER OR FILES IN LINUX?

Linux files can be accessed by either Absolute Path or Relative Path

Absolute Path

It is the complete path to any file or directory. It always starts with a ‘/’.

Relative Path

A Path which is relative to current working directory. Some special characters used at the starting of Relative Path are –

  • .       Current Directory
  • ..      Parent Directory
  • ~     Home Directory
  • –      Previous Directory

Linux Tutorials: relative-path

HOW TO NAVIGATE INTO FILESYSTEM IN LINUX?

To navigate Linux filesystem following three commands are needed.

  • pwd – To print current working directory.
  • ls – To List directory contents.
  • cd – To change Directory.
$ pwd
$ ls
$ cd /
$ cd /etc
$ cd /var/spool/mail
$ ls /var/log
$ cd ~
$ cd .
$ cd ..
$ cd ../etc/ssh
$ cd ../../var/spool/mail
$ cd ../../boot/grub2
$ cd -
$ cd

 

KNOW ABOUT FILE CREATION IN LINUX

Files can be created with ‘touch’ command.

$ touch foo.txt
$ ls
$ touch bar.txt /tmp/ace.txt ../../tmp/mono.txt
$ ls

Actually touch is not used to create a file but is used to change the timestamps of a file or a directory.

$ file foo.txt
$ stat foo.txt
$ touch foo.txt
$ stat foo.txt

The file command displays the type of a file based on certain tests including the pattern matching as per the patterns stored in /usr/share/misc/magic file.

The stat command displays the file statistics including the data from inode table.

KNOW ABOUT DIRECTORY CREATION IN LINUX

Directories can be created with ‘mkdir’ command.

# mkdir /testdir
$ mkdir -v /tmp/testdir
$ mkdir -pv testdir/nesteddir

Option v displays a message that the directory is created.
Option p will create the parent directory tree if does not exist.

WHAT IS PATTERN MATCHING OR GLOBBING IN LINUX?

BASH has pattern matching or wildcards feature making managing files easier. It is also called globbing. Globbing expands the wildcards into a list of matching path names.

*		Any string of 0 or more characters
?		Any single character
~		Current user's home directory
~username	Given user's home directory
[abc]		Any one character in enclosed class
[!abc]		Any one character not in enclosed class
[[:alpha:]]	Any alphabetic character
[[:digit:]]	Any digit, 0-9
[[:lower:]]	Any lower case alphabetic character
[[:upper:]]	Any upper case alphabetic character

The following commands will help us understand the globbing.

$ mkdir glob; cd glob
$ touch alfa bravo charlie delta echo able baker cast dog easy
$ ls
$ ls a*
$ ls *a*
$ ls [ac]*
$ ls ????
$ ls ?????
$ echo anushesh | tr [[:lower:]] [[:upper:]]

Tilde expansion

$ ls ~/glob
$ echo ~/glob

Brace expansion

$ echo {a,b,c,d,e}.log
$ echo file{1..5}.txt
$ echo file{a..e}.txt
$ echo file{1,2}{a,b}.txt
$ echo file{a{1,2},b{3,4},c}.txt

Command Substitution

$ echo "Today is `date +%A`"
$ echo "The time is $(date +%M) minutes past $(date +1%p)."

Sometimes we do not want the arguments to expand and use them literally. In such cases, we use backslash.

$ echo $SHELL
$ echo \$SHELL
$ echo '$SHELL'
$ echo "$SHELL"

HOW TO REMOVE FILES AND DIRECTORIES IN LINUX?

Files can be removed with ‘rm’ command.

# rm /testfile
$ rm -v /tmp/testfile
$ rm -vf testfile

Empty directories can be removed with ‘rmdir’ command. To remove non-empty directories use ‘rm’ command.

# rmdir /testdir
$ rmdir -v /tmp/testdir
$ rm -rvf testdir
Option f forcefully implies the operation.
Option r will recursively traverse the directory and remove files from inside-out.
Files/Directories can be copied with cp command.

HOW TO COPY FILES AND DIRECTORIES FROM ONE LOCATION TO ANOTHER?

Files/Directories can be copied with cp command.
$ mkdir ~/cptest
$ cd ~/cptest
$ touch file{1,2,3,4,5,6,7,8,9}
$ mkdir dir{1..9}
$ cp file1 dir1
$ cp -v file2 file3 dir2
$ cp -v file3 newfile
$ cp -v f* dir3
$ cp -v [nf]* dir4
$ cp -rv dir1 dir5
$ cp -rv dir2 dir3 dir6
$ cp -rv dir4 newdir
$ cp -rv d*
We are using regular expression for creating files and directories.
file{1,2,3,4,5,6,7,8,9} will first expand into file1 file2 file3 file4 file5 file6 file7 file8 file9 and then it will be executed by touchthereby creating nine files. Similarly, nine directories will be created.

HOW TO MOVE FILES AND DIRECTORIES IN LINUX?

Files/Directories can be moved with commandmv.

$ mkdir ~/mvtest
$ cd ~/mvtest
$ touch file{1..9}
$ mkdir dir{1..9}
$ mv file1 dir1
$ mv -v file2 file3 dir2
$ mv -v file4 newfile
$ mv -v [nf]* dir4
$ mv -v dir1 dir5
$ mv -v dir2 dir3 dir6
$ mv -v dir4 newdir
$ mv -v d*

READING FILES

To read a regular file we have many commands. cat command is used mostly to read a file.
wc is used to count the lines, words and characters in the file.
nl is used to number the lines of a file but it does not count blank lines.

 

$ cat /etc/issue
$ cat /etc/hosts
$ cat /etc/issue /etc/hosts
$ cat -n /etc/issue
$ wc /etc/issue
$ nl /etc/issue
$ tac /etc/issue
$ cat /etc/services

Option n of cat will display the file with line numbers just like nl command.

READING FILE WITH PAGERS

It is not a good idea to read a huge file with cat command as it dumps the whole file on screen and screen has limited buffer so it is not possible to read the whole file. Instead, we use pagers. There are two of them – more and lessmore does not support for navigation keys but less does.

$ more /etc/services
$ less /etc/services

Return key scrolls down 1 line, Spacebar scrolls down 1 page and ‘b’ scrolls up 1 page in both more and less.

READING LIMITED LINES OF FILE

It is also possible to read limited number of lines from beginning of the file or end of the file with head and tail respectively.

$ head /etc/services
$ head -n 4 /etc/services
$ tail /etc/services
$ tail -n 2 /etc/services

Option n with both head and tail is used to specify the number of lines to display.

SEARCHING TEXT IN FILE

 To search text in a file use grep command.
$ grep root /etc/passwd
$ grep http /etc/services
$ grep ^http /etc/services
$ grep http$ /etc/services
$ grep ^$ /etc/services

Symbol ^ indicates the start of line and symbol $ indicates the end of line.

Is there any Help available in Linux!!

Manual Pages

Manual Pages is one stop help for the commands and utilities in Linux OS. To read the manual pages man command is used.

$ man uptime
$ man dmidecode

One line descriptions of manual pages can be displayed using whatis command.

$ whatis uptime
$ whatis dmidecode

Manual Pages database can be used to search for the short description of the command. It can also be used to search for the command if you don’t know the command itself by searching for keywords.

$ man -k copy
$ man -k authentication
$ apropos move

In order to create the Manual Pages database run commandmandb as root user.

# mandb

Manual Pages has 9 sections in which the manual pages are classified.

  1. Executable programs or shell commands
  2. System calls (functions provided by the kernel)
  3. Library calls (functions within program libraries)
  4. Special files (usually found in /dev)
  5. File formats and conventions eg /etc/passwd
  6. Games
  7. Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)
  8. System administration commands (usually only for root)
  9. Kernel routines [Non-standard]

Non-standard sections are as given below.

  • 0
    Header files
  • 0p
    Header files (POSIX)
  • 1p
    Executable programs or shell commands (POSIX)
  • 3n
    Network Functions
  • 3p
    Perl Modules
  • l
    Local documentation
  • n
    New manpages

Sometimes we have the same command name and file name like in case of passwd. Sometimes we have the same name for command and library call like in case of printf. In such case, we have to mention section number to see the respective manual page entry.

$ man -f passwd
$ man passwd
$ man 5 passwd
$ man printf
$ man 3 printf

To read the history of Manual Pages click Here

INFORMATION PAGES

GNU Information Pages are also helpful to find about what the command does.

$ pinfo uptime

DOCUMENTATION IN /USR/SHARE/DOC

The documentation can be read using file reading commands or by using a text editor.

Let’s understand the SHELL and its working

Details about Command Line Interface

In early days of computing, there was no Graphical User Interface. There was only CLI to interact with the computer. Computers back then were very costly and providing personal workstations to individuals was not economical. Mainframe Computers were used for computing by attaching terminal devices to them so that multiple users can access the same mainframe from each terminal device.

A Terminal device is a set of input and output device i.e. it is a user interface. It used to be connected to mainframes via a serial port. One such terminal device was VT-100.

In modern computing age, computers are within the reach of common people and so we do not need to use terminals anymore.

Linux was designed to work with mainframes and so it had the feature to work with terminals. As there is no need for us to use physical terminals anymore we have the feature of “Virtual Terminal” or “Virtual Console” in Linux.

A Virtual Terminal is the user interface where the functionality of a physical terminal is implemented in software. Having more than one virtual terminal allows the administrator to switch to another terminal if necessary.

In all Linux, Distros VTs are found. By default 6 VTs are enabled which can be accessed through the key combinations displayed in above image. GUI is running on first VT if DE is installed and the system is set to boot into GUI.

Linux Tutorials: terminals key shortcuts

 

How to login to Virtual Terminal

Access a Virtual terminal where no GUI is running. You will be presented with a login prompt. Type your username and password and on successful authentication, you will get a Shell.

Linux Tutorial: cli-login image
cli-login image

 

Once Shell gets started you will see a cursor waiting for a command from the user. This is called a shell prompt. Shell prompt ends with a $symbol, when a regular user is logged on ,or with # symbol when a super user is logged on. On shell prompt, you will also be seeing the current directory you are working in. When a user logged in, the current directory is set to user’s home directory which is displayed as tilde symbol~

 

Know about  USER ACCOUNTS

Linux user accounts have following properties.

  • Every User has a UID
  • Every User has a primary group
  • Every Group has a GID

Linux has three types of user accounts – Super, System, and Regular.

Super Account

  • UID = 0
  • GID = 0
  • Has All Privileges

 

System Accounts

  • UID = 1 – 999
  • GID = 1 – 999
  • Has Limited Privileges
  • Cannot Login into the system
  • Used to run background processes called daemons

 

Regular Accounts

  • UID = 1000 – 60000
  • GID = 1000 – 60000
  • Has Limited Privileges

 

SHELL

In order to perform some task in CLI we have specialized utilities which run in text mode and generate text mode output. When we want to use these utilities we type their name on shell prompt as commands. Shell then searches for the executable file of these commands and once its found that, it will execute them. After the command has finished execution the control is given back to shell which again waits for user to input commands on shell prompt.

In a nutshell, shell is a command interpreter.

Different types Shells are available in Linux.

  • sh – Original Unix Shell
  • bash – Bourne Again Shell
  • csh – C Shell
  • tcsh – Turbo C Shell
  • ksh – Korn Shell
  • zsh – Z Shell

BASH is default shell available in most of the Linux distributions.

cat /etc/shells lists the available shells on your system. The Shell currently being used can be verified with commandecho $0.

Commands entered at the shell prompt have three basic parts:

  • Command to run
  • Options to adjust the behavior of the command generally prepended with one or two dash symbols (-, –)
  • Arguments which are typically the targets of the command

List of General Commands we use

To print UID, GID, Groups, and SELinux contexts

$ id
$ id root

To print name of current logged in user

$ whoami

 

To print names of all logged in users

$ who
$ who am i

Same as who with extra information about what the user is doing

$ w

 

To print names of all logged in users

$ users

 

To print names of all groups to which the user currently belongs

$ groups

 

To print name of current terminal

$ tty

 

To print system uptime along with the load average

$ uptime
$ uptime -p

 

To print or change date and time

$ date
$ date +"%d-%m-%Y"

 

To prints or set date and time

$ timedatectl

 

To print calendar

$ cal
$ cal -3
$ cal 2017
$ cal 5 2017
$ cal 15 5 2017

 

To print system information

$ uname
$ uname -a

 

To print text on screen

$ echo 'Hello Linux!'
To sleep for given number of seconds
$ sleep 5

To change the terminal

$ chvt 3

To print command history

$ history
$ history -c

To clear the screen

$ clear

To change user password

$ passwd
# passwd student

Commands regarding the System Information

 To print CPU Information
$ lscpu

To list PCI devices

$ lspci

To list USB devices

$ lsusb

To print memory usage

$ free
$ free -m

To print or change machine name

$ hostname
$ hostname neo.matrix.com

To print or set machine name

$ hostnamectl
$ hostnamectl set-hostname neo.example.com

To print BIOS information

$ dmidecode

Introduction to Linux Operating System

Operating System: Introduction

The operating system is the group of software that works together to operate the underlying hardware and provide an interface for user applications. User applications like media player, web browsers, Office Suite or others cannot directly access the computer hardware. It is the OS on which these applications depends to complete their job. In short, OS sits between the computer hardware and user applications.

We never truly use the Operating system, instead, we use applications to perform our work. Let’s say for example, we use Firefox for browsing internet, VLC player to play our media files, LibreOffice to perform our office work, ‘ls’ command to display directory listing, ‘ps’ command to display process status, etc. These are just bunch of examples, Operating System does a lot more.

Software that together constitutes to form an Operating system includes Kernel, Standard C Library, Compiler, Assembler, Shell, Text Editor, DE, etc. Of all these software, Kernel has the most importance.

Leading Operating Systems are: Linux based OS, Windows, Macintosh, Unix, Android

Linus : Introduction to operating system
Introduction to operating system

KERNEL:

Kernel performs some key tasks in order for the computer to be operable at all. This Kernel is responsible for talking to computer hardware. Some of the key tasks that Kernel performs are Process Management, Memory Management, Device Management, File System Management, etc.

PROCESS MANAGEMENT

CPU is one of the most important hardware part which is responsible for the execution of all instructions. Instructions which come from the running processes. Multitasking OS facilitates the execution of multiple processes at the same time by taking advantage of the time-sharing concept. Since multiple processes are running, they will have so many instructions to be executed by the CPU in very less time. This Kernel manages these processes by using different CPU scheduling algorithms. Kernel lines up the processes for getting their instructions to be executed by the CPU and allocates time slices to them.

Kernel is also responsible for handling interrupts.

Linux Tutorials : Process Management in Operation System
Process Management in Operation System

MEMORY MANAGEMENT

Every process that runs needs some space in main memory i.e. RAM. Storage space in RAM is limited and hence we need to properly manage the space of main memory. The kernel takes care of the memory management by implementing memory management algorithms. The kernel keeps the record of used and free main memory and allocates space to the processes from free memory as their need.

DEVICE MANAGEMENT

Every Physical device has its own hardware controller. Hardware controllers can stop, start, initialize or diagnose the device. The software that manages the hardware controller is called Device Driver. Device drivers are kept in the kernel as a module. Since drivers are kept as modules it is easy to add and remove functionality from Linux kernel as per requirement.

USER INTERFACE

OS provides an interface to the users in order to interact with the OS. The interface can be CLI or GUI. A user gives instructions to the OS with the interface being provided.

When using Linux these days, the user is usually directed to GUI. GUI in Linux is provided by the “X Window System” or “X11” and “Wayland” (under development).

When in GUI you get a Desktop Environment (DE) like Gnome, KDE, XFCE, LXDE, Cinnamon, Enlightenment, etc and a mouse pointer to interact with it. DEs themselves are a group of software consisting of many entities like Display Manager, File Manager, Web Browser, Multimedia Player, Office Productivity Suite, Email Client, Photo Manager, System Preferences applications and much more.

Every Linux systems administrator has to use the CLI sooner or later. When GUI fails to start the user is presented with CLI only, so we need to be able to handle CLI for surviving in these circumstances.

When in CLI we get Shell to interact with the OS. There are many different types of shells available including bash, csh, tcsh, etc. In CLI we pass the input to the OS with a keyboard device and the output or error is displayed on screen. In order to perform some task in CLI we have specialized utilities which run in text mode and generate text mode output. When we want to use these utilities we type their name on shell prompt as commands. We frequently use certain utilities like: cd, ls, pwd, cp, mv, rm, touch, mkdir, etc

LINUX

Linux is an operating system Kernel. Kernel alone is of no use unless it is packed together with other programs. Many companies and organizations tied together user space programs and Linux kernel to build what we know as “Linux Operating System”.

Operating systems with Linux kernel are also called “Linux Distributions” or “Linux Distros”. Some of the widely popular Linux Distros are: Debian, Red Hat Enterprise Linux, Fedora, Ubuntu, Slackware, SuSe, Mint, Arch, Gentoo.

Linux Installation Guide

How to  create Bootable Media

We are now going to install CentOS 7 from a bootable USB drive. To create a bootable USB drive of CentOS 7 we need

  • CentOS 7 iso image file
  • A USB drive with minimum 4GB space

Follow the procedure given below to create CentOS 7 bootable USB drive in very easy way.

Assuming your USB drive path is like /dev/sdb and absolute path of CentOS 7 iso is /CentOS7.iso.

  1. Plug in the USB drive
  2. Unmount the USB drive partition if it is automatically mounted
  3. Use “fdisk” to delete any partition created in the USB drive and create a single VFAT partition
  4. Format the newly created VFAT partition with “mkfs.vfat” command
  5. Use “dd” command to write the CentOS 7 iso image file to the USB drive.
    dd if=<Path to CentOS 7 iso> of=<USB drive path>
dd if=/CentOS7.iso of=/dev/sdb

INSTALLATION PROCEDURE FOR CENTOS 7

Start the machine and boot from a USB drive. You will see the menu as given in below image. Here we have to select “Install CentOS 7” menu entry.

Linux Tutorial : Linux Installtion

 

Once CentOS system installer Anaconda starts, we will be asked to set the language preferences to use during installation.

Select the language as you want and click on “Continue” button.

Linux Tutorial : Linux Installation

 

Select “Server with GUI” from “Software selection” and click on “Done” button.

Linux Tutorial : Linux Installation

 

In “Installation Destination” select the disk which you want to use for installation of CentOS. Also, select “I will configure partitioning” on the same menu and click on “Done” button.

Linux Tutorials : Linux Installation

Create three partitions as shown in the image.

/boot -> 500MB -> xfs
/     -> 12GB  -> xfs
swap  -> 256MB -> swap

After creating partitions click on “Done” button.

Linux Tutorial : Linux Installation

 

Click on “Begin Installation” button once all the components have been configured correctly.Linux Installation

 

The installation process will start now and you will need to set a password for “root” user and create a new regular user.

Linux Installation

 

Know about I/O Redirections and Pipe

I/O REDIRECTION

There are three standard devices in CLI, they are Standard Input, Standard Output and Standard Error.

Default Standard Input device is Keyboard. The screen is the default Standard Output and Standard Error device. Meaning the input is generally given from Keyboard and output and errors are generally displayed on Screen.

Sometimes it is required to pass the input from a file. Similarly, sometimes it is required to store the output and error in the file. In such scenario, IO redirectors are used. The IO redirectors are as follows.

 

  • < – Input Redirector
  • > – Output Redirector
  • 2> – Error Redirector
  • &> – Error and Output both Redirector
$ cat /etc/issue /etc/resolve.conf > output
$ cat /etc/issue /etc/resolve.conf 2> error
$ cat /etc/issue /etc/resolve.conf > out 2> err
$ cat /etc/issue /etc/resolve.conf &> both
$ mail root@localhost
Subject: Test
This is the body of the mail.
.
$ mail -s "Test Mail" root@localhost < /etc/passwd

PIPE

Pipe (|) takes the output of the command on the LHS and pass it as input to the command on the RHS.

$ head /etc/services | tail -n 3
$ cat -n /etc/services | head -n 70 | tail -n 10
$ dmidecode | less
$ cat -n /etc/services | head -n 70 | tail -n 10 | tee output.txt

There is one more command called tee command, which saves the output of previous command in a file and also prints it on screen.