Linux Commands
Linux Commands
Linux Commands
ls
ls with no option list files and directories in bare format where we won’t be able to view details like file
types, size, modified date and time, permission and links etc.
cat
cat (short for “concatenate“) allows us to create single or multiple files, view contain of file, concatenate
files and redirect output in terminal or files.
more to view a text file one page at a time, press spacebar to go to the next page
more file.txt # show the document one page at a time
more -num filename # show the document page few lines as specified (-num)
a) You can navigate the page up/down using the less command and not possible in more
command.
b) You can search a string in less command. (use /keyword to search)
c) “more” was fairly limited, and additional development on “more” had stopped
d) it uses same functions as vi editor
head a) head -n n file.txt The head command, as the name implies, print the top N number of
lines of the given input. By default, it prints the first 10 lines of the specified files.
head -n 5 file.txt (or) head -5 file.txt
# Prints first 5 line of file.txt
b) head -c num file.txt Prints the first ‘num’ bytes from the file specified. Newline count
as a single character, so if head prints out a newline, it will count it as a byte. num is
mandatory to be specified in command otherwise displays an error.
head -c 6 file.txt
tail a) tail -n n file.txt The tail command, as the name implies, print the last N number of lines
of the given input. By default, it prints the first 10 lines of the specified files.
tail -n 5 file.txt (or) tail -5 file.txt
# Prints last 5 line of file.txt
b) tail -c num file.txt Prints the last ‘num’ bytes from the file specified. Newline count as a
single character, so if tail prints out a newline, it will count it as a byte. num is mandatory
to be specified in command otherwise displays an error.
tail -c 6 file.txt
c) To continuously print a file which is getting updated like log file.
tail -f filename
cd Use the "cd" command to go to a directory/change the current directory. For example, if you
are in the home folder, and you want to go to the downloads folder, then you can type in “cd
downloads”.
mkdir Use the mkdir command when you need to create a folder or a directory.
mkdir /home/sample
rmdir rmdir is use to delete empty directory, to remove non-empty directory use rm
rm Use the rm command to delete files and directories. But rm cannot simply delete a directory.
Use “rm -r” to delete a directory. In this case, it deletes both the folder and the files in it.
rm file_name
rm -r directory
touch The touch command is used to create a file. It can be anything, from an empty txt file to an
empty zip file.
touch filename.txt
pwd Command to know present working directory. When you first open the terminal, you are in
the home directory of your user. To know which directory you are in, you can use
the “pwd” command. It gives us the full path, which means the path that starts from the root.
mv mv command to move files through the command line. We can also use the mv command to
rename a file.
mv old_filename new_filename
move all files from source to destination
mv /source_path/*.* /destination_path/
locate The locate command is used to locate a file in a Linux system, just like the search command in
Windows. This command is useful when you don't know where a file is saved or the actual
name of the file. Using the -i argument with the command helps to ignore the case
locate file_name
cp cp command used to copy files from source location to destination. It takes two arguments:
The first is the location of the file to be copied, the second is where to copy.
cp /source_path/filename /destination_path/
output:
linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
output:
unix is great os. linux is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.
output:
linux is great os. linux is opensource. linux is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.
The above sed command replaces the third, fourth, fifth… “unix” word with “linux” word in a
line. (from 3rd occurance to all till end of line)
output:
The /p print flag prints the replaced line twice on the terminal. If a line does not have the
search pattern and is not replaced, then the /p prints that line only once.
output:
linux is great os. unix is opensource. unix is free os.
linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
Use the -n option along with the /p print flag to display only the replaced lines. Here the -n
option suppresses the duplicate rows generated by the /p flag and prints the replaced lines
only one time.
output:
linux is great os. unix is opensource. unix is free os.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
8) Write a sed command to print the lines that do not contain the word "run"?
sed -n '/run/!p' file.txt
Here the sed command replaces the lines with range from 1 to 3.
Output:
Output:
. current directory
awk
The awk command in UNIX is a command for cutting out the sections column with using field separator from
each line of files and writing the result to standard output.
WHAT ARE THE OPERATIONS OF AWK?
a) Scans a file line by line
b) Splits each input line into fields
c) Compares input line/fields to pattern
d) Performs actions on matched lines
Useful For:
a) Transform data files
b) Produce formatted reports
Programming Constructs:
a) Format output lines
b) Arithmetic and string operations
c) Conditionals and loops
Consider the following text file as the input file for all cases below.
$cat > employee.txt
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
1) Default behavior of Awk: By default Awk prints every line of data from the space separated field of file.
awk '{print $1}' employee.txt
(or)
awk -f “ “ ‘{print $1}’ employee.txt
Output:
Ajay
Sunil
Varun
Amit
Output:
45000
25000
50000
47000
3) print all columns except the first one column:
awk '{$1=""; print $0}' file
Output:
ajay manager account 45000
varun manager sales 50000
amit manager account 47000
NR NR command keeps a current count of the number of input records. Remember that records are
usually lines. Awk command performs the pattern/action statements once for each record in a file.
NF NF command keeps a count of the number of fields within the current input record.
FS FS command contains the field separator character which is used to divide fields on the input line.
The default is “white space”, meaning space and tab characters. FS can be reassigned to another
character (typically in BEGIN) to change the field separator.
RS RS command stores the current record separator character. Since, by default, an input line is the
input record, the default record separator character is a newline.
OFS OFS command stores the output field separator, which separates the fields when Awk prints them.
The default is a blank space. Whenever print has several parameters separated with commas, it will
print the value of OFS in between each parameter.
ORS ORS command stores the output record separator, which separates the output lines when Awk
prints them. The default is a newline character. print automatically outputs the contents of ORS at
the end of whatever it is given to print.
COMMAND OUTPUT
a) Date and time of 2 years ago. date --date="2 year ago" Sat Oct 10 23:42:15 PDT 2015
b) Date and time of 5 seconds ago. date --date="5 sec ago" Tue Oct 10 23:45:02 PDT 2017
c) Date and time of previous day. date --date="yesterday" Mon Oct 9 23:48:00 PDT 2017
d) Date and time of 2 months ago. date --date="2 month ago" Thu Aug 10 23:54:51 PDT 2017
e) Date and time of 10 days ago. date --date="10 day ago" Sat Sep 30 23:56:55 PDT 2017
COMMAND OUTPUT
a) Date and time of upcoming date --date="next tue" Tue Oct 17 00:00:00 PDT 2017
particular week day.
b) Date and time after two days. date --date="2 day" Fri Oct 13 00:05:52 PDT 2017
c) Date and time of next day. date --date="tomorrow" Thu Oct 12 00:08:47 PDT 2017
d) Date and time after 1 year on the date --date="1 year" Thu Oct 11 00:11:38 PDT 2018
current day.
3) -s or –set Option: To set the system date and time -s or –set option is used.
date --set="date to be set"
date --set="Tue Nov 13 15:23:34 PDT 2018"
date
Output:
Tue Nov 13 15:23:34 PDT 2018
4) List of Format specifiers used with date command:
COMMAND OUTPUT
date "+%D" 10/11/17
date "+%D %T" 10/11/17 16:13:27
date "+%Y-%m-%d" 2017-10-11
date "+%Y/%m/%d" 2017/10/11
date "+%A %B %d %T %y" Thursday October 07:54:29 17
Special Variables
These are special shell variables which are set internally by the shell and which are available to the user:
VARIABLE DESCRIPTION
These variables correspond to the arguments with which a script was invoked. Here n
is a positive decimal number corresponding to the position of an argument (the first
$n
argument is $1, the second argument is $2, and so on). User flower braces for double or
more digits like ${10}, ${100}
The process ID of the current shell. For shell scripts, this is the process ID under which
$$
they are executing.
All the arguments are individually double quoted. If a script receives two arguments,
$@
$@ is equivalent to $1 $2.
All the arguments are double quoted. If a script receives two arguments, $* is
$*
equivalent to $1 $2.
4) Schedule a Job for More Than One Instance (e.g. Twice a Day)
executes the specified script at 11:00 and 16:00 on every day
00 11,16 * * * /home/ramesh/bin/incremental-backup
SSH The ssh command provides a secure encrypted connection between two hosts over an insecure
network. This connection can also be used for terminal access, file transfers, and for tunneling
other applications.
Note: after running the above command new to enter the password through console and you get
successfully logged-in to another server.
Ssh-keygen is a tool for creating new authentication key pairs for SSH. Such key pairs are
used for automating logins, single sign-on, and for authenticating hosts.
ping Ping a remote host by sending packets. Used to check whether the remote server is up and
running.
ping hastname
ping IP_addres
curl curl is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS,
FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE). The command is designed to work without
user interaction. It offers proxy support, user authentication, FTP uploading, HTTP posting, SSL
connections, cookies, file transfer resume, Metalink, and many other features, listed below
2) Download a File
If you want to download a file, you can use curl with the -O or -o options. The former will save
the file in the current working directory with the same name as in the remote location, whereas
the latter allows you to specify a different filename and/or location.
curl -O http://yourdomain.com/yourfile.tar.gz # Save as yourfile.tar.gz
curl -o newfile.tar.gz http://yourdomain.com/yourfile.tar.gz # Save as newfile.tar.gz
free
To see the size of the memory in (MB) Megabytes use option as -m.
free -m
top The top command also gives you a real-time update on how much of your swap
space is being used.
One of the things top is very good for is discovering Process ID (PID) numbers of
services that might have gotten out of hand. With those PIDs, you can then set
about to troubleshoot (or kill) the offending tasks.
vmstat Another very handy tool to have at your disposal is vmstat. This particular
command is a one-trick pony that reports virtual memory statistics. The vmstat
command will report stats on: Processes, Memory, Paging, Block IO, Traps, Disks
and CPU
/proc/meminfo The next way to check memory usage is to read the /proc/meminfo file. Know
that the /proc file system does not contain real files. They are rather virtual files
that contain dynamic information about the kernel and the system.
mount To mount a file system, you should first create a directory and mount it as shown
below.
# mkdir /u01
# mount /dev/sdb1 /u01
kill Use kill command to terminate a process. First get the process id using ps -ef
command, then use kill -9 to kill the running Linux process as shown below. You
can also use killall, pkill, xkill to terminate a unix process.
bg %0
lsof
1) List User Specific Opened Files: lsof -u tecmint
2) Find Processes running on Specific Port: lsof -i TCP:22
3) List Open Files of TCP Port ranges 1-1024: lsof -i TCP:1-1024
4) Find Out who’s Looking (which user) What Files and Commands: lsof -i -u username
5) List all Network Connections ‘LISTENING & ESTABLISHED’: lsof -i
6) List open files by pid: lsof -p 351
7) List processes using a particular file: lsof filename (or) fuser filename
Permission and user related commands
chmod
chmod is used to change the permissions of files or directories.
User Group Other Chmods:
Read 4 4 4 777 = rwxrwxrwx
Write 2 2 2 755 = rwxr-xr-x
Execute 1 1 1 644 = rw-r--r--
U G O 700 = rwx------
X X X 750 = rwxr-x---
3. Make a file readable and writable by the group and others. : chmod go+rw file.txt
4. Make a shell script executable by the user/owner. : chmod u+x file.sh
5. Allow everyone to read, write, and execute the file and turn on the set : chmod =rwx,g+s file.sh
group-ID.
6. Recursively (-R) Change the permissions of the directory myfiles, and : chmod -R 755 folder
all folders and files it contains, to mode 755: User can read, write, and
execute; group members and other users can read and execute, but
cannot write.
7. Set the permission of file.txt to "read and write by everyone." : chmod 666 file.txt
Chown
chown command is used to change the owner and group of a file or directory.
1) To change owner to oracle and group to dba on a file. i.e Change both owner and group at the same
time.
chown oracle:dba dbora.sh
adduser / useradd
To add/create a new user, all you’ve to follow the command ‘useradd‘ or ‘adduser‘ with ‘username’. The
‘username’ is a user login name, that is used by user to login into the system.
Only one user can be added and that username must be unique (different from other username already
exists on the system).
For example, to add a new user called ‘newuser‘, use the following command.
Passwd
useradd newuser
passwd
1) change your password from command line using passwd. This will prompt for the old password
followed by the new password.
passwd
2) Super user can use passwd command to reset others password. This will not prompt for current
password of the user.
passwd USERNAME
3) Remove password for a specific user. Root user can disable password for a specific user. Once the
password is disabled, the user can login without entering the password.
passwd -d USERNAME
whereis When you want to find out where a specific Unix command exists (for example, where does
ls command exists?), you can execute the following command.
5) To zip files
zip [options] zipfile files_list
zip myfile.zip filename1.txt filename2.txt …..
STEP 1: BIOS
BIOS determine all the list of bootable devices available in the system. Prompts to select bootable device
which might be Hard Disk, CD/DVD-ROM, Floppy Drive, USB Flash Memory Stick etc. Operating System tries to boot
from Hard Disk where the MBR contains primary boot loader.
GRUB Stage 2:
This is responsible for loading kernel from /boot/grub/grub.conf and any other modules needed and Loads a GUI
interface i.e. splash image located at /grub/splash.xpm.gz with list of available kernels where you can manually
select the kernel or else after the default timeout value the selected kernel will boot The original file is
/etc/grub.conf of which you can observe a symlink file at /boot/grub/grub.conf
STEP 3: Kernel
This is the heart of operating system responsible for handling all system processes. Kernel is loaded in the following
stages: Kernel as soon as it is loaded configures hardware and memory allocated to the system. Next it
uncompresses the initrd image (compressed using zlib into zImage or bzImage formats) and mounts it and loads
all the necessary drivers. Loading and unloading of kernel modules is done with the help of programs like insmod,
and rmmod present in the initrd image. Looks out for hard disk types be it a LVM or RAID. Unmounts initrd image
and frees up all the memory occupied by the disk image. Then kernel mounts the root partition as specified in
grub.conf as read-only. Next it runs the init process
1) FILTER – this is the default table, which contains the built-in chains for:
▪ INPUT – packages destined for local sockets
▪ FORWARD – packets routed through the system
▪ OUTPUT – packets generated locally
2) NAT – a table that is consulted when a packet tries to create a new connection. It has the following built-in:
▪ PREROUTING – used for altering a packet as soon as it’s received
▪ OUTPUT – used for altering locally generated packets
▪ POSTROUTING – used for altering packets as they are about to go out
3) MANGLE – this table is used for packet altering. Until kernel version 2.4 this table had only two chains, but
they are now 5:
▪ PREROUTING – for altering incoming connections
▪ OUTPUT – for altering locally generated packets
▪ INPUT – for incoming packets
▪ POSTROUTING – for altering packets as they are about to go out
▪ FORWARD – for packets routed through the box