Linux Interview Questions

Updated: Jul 26, 2020



1) What is Linux?

Linux is an operating system, which is based on Linux Kernel. It is an open-source operating system where it can run on different hardware platforms. It provides a free and low-cost operating system for users. It is a user-friendly environment where they can easily modify and create variations in the source code.


2)What is Linux Kernel?

The Linux kernel is the main component of a Linux operating system (OS) and is the core interface between a computer’s hardware and its processes. It communicates between the 2, managing resources as efficiently as possible.

What the kernel does

The kernel has 4 jobs:

Memory management: Keep track of how much memory is used to store what, and where

Process management: Determine which processes can use the central processing unit (CPU), when, and for how long

Device drivers: Act as mediator/interpreter between the hardware and processes

System calls and security: Receive requests for service from the processes.


3) What is Shell?

Shell is a computer program which acts as an interface between the user and the kernel. Users can communicate with the kernel by writing programs, commands and scripts on the shell. It accepts human-readable commands and converts them into the kernel understandable language.


4)What are the basic components of Linux?

Basic components of Linux

  1. Kernel: It is the core component of the Linux, it acts as an interface between software and hardware.

  2. Shell: It acts as an interface between the user and the Kernel.

  3. GUI: It stands for Graphic User Interface, which is another way for the user to interact with the system. But it is unlike images, buttons, text boxes for interaction.

  4. System Utilities: These are the software functions that allow users to manage the computer.

  5. Application Programs: Set of functions designed to perform a set of tasks.

5) Differentiate between LINUX and UNIX?



6) How can you determine the total memory used by LINUX?

It is always required to keep a check on the memory usage in order to find out whether the user is able to access the server or the resources adequately. There are roughly 5 methods that determine the total memory used by Linux.

This is explained as below:

  • Free command: This is the most simple command to check memory usage. For Example, ‘$ free –m’, the option ‘m' displays all the data in MBs.

  • /proc/meminfo: The next way to determine memory usage is to read /proc/meminfo file. For Example, ‘$ cat /proc/meminfo’

  • Vmstat: This command basically lays out the memory usage statistics. For Example, ‘$ vmstat –s’

  • Top command: This command determines the total memory usage as well as also monitors the RAM usage.

  • Htop: This command also displays memory usage along with other details.

7) What are the default ports used for SMTP, DNS, FTP, DHCP, SSH, and squid?

Details mentioned below

Service Port

Telnet 23

SMTP 25

DNS 53

FTP 20(Data Transfer) 21(Connections Established)

DHCP 68(dhcp client), 67(DHCP server)

SSH 22

Squid 3128


8)Can you draw the Linux architecture?

9) what happened when system starts?

it executes four script

a) setting variable

1-->/etc/profile

2-->/etc/bashrc

b) setting path

1--> ~/.bash_profile

2-->~/.bashrc

10) In how many ways shell script execute?

a) it will create child process

1-->sh

2-->./

b)it will not creating child

1) .

2) source


11) Sed (stream editor) related interview questions ?

How to get the list of files alone in a directory in Linux?

ls -lrt | grep ^-


How to get the list of directory alone in Linux?

ls -lrt| grep "^d"


How to get list of hidden directory ?

ls -d .*/

How to list the only linked file ?

ls -lrt| grep ^l


How to delete blank Line from a file using sed command?

sed '/^$/d' filename


How to delete Starting from 3rd line and every 2nd line from there from sed command?

sed '3~2d' filename


How to delete the line which matches the given pattern from input?

sed /Sysadmin/d filename


If 3rd line matches the pattern “Hardware”, so it prints from 3rd line to 6th line.

sed -n '/Hardware/,6p' filename


How to deletes the line from which matches the given pattern and 2 lines next to that?

sed '/Storage/,+2d' filename


If 4th line matches the pattern “Security”, so it prints from 3rd line to 4th line.

sed -n '3,/Security/p' filename

How to print from the line matches the given pattern to end of file?

sed -n ‘/PATTERN/,$p’ filename

How to print the lines which matches the pattern and next N lines following the matched line?

sed -n '/Storage/,+2p' filename


How to Print the section of file between two regular expression (including the matched line )?

sed -n ‘/P1/,/P2/p’ filename


How to substitute Only 2nd Occurrence of a Word Using sed ?

sed 's/Linux/Linux-Unix/2' filename

How to write Changes to a File and Print the Changes Using sed ?

sed -n 's/Linux/Linux-Unix/gpw ' filename


12)What is INODE ?

· An inode is a data structure on a filesystem on Linux and other Unix-like operating systems that stores all the information about a file except its name and its actual data. A data structure is a way of storing data so that it can be used efficiently.

· An Inode number points to an Inode. An Inode is a data structure that stores the following information about a file :

  • · Inode number

  • Access control list

  • · Extended attribute

  • · Direct/indirect disk blocks

  • · Number of blocks

  • · File access, change and modification time

  • · File deletion time

  • · File generation number

  • · File size

  • · File type

  • · Group

  • · Number of links

  • · Owner

  • · Permissions

  • · Status flags

To get a listing of an inode number, use the following command:

Code:

$ ls –i filename

You can use the “stat” command to get more information than the inode number:

Code:

$ stat filename


13) what are SOFT LINKS AND HARD LINKS ?

A link in UNIX is a pointer to a file. Like pointers in any programming languages, links

in UNIX are pointers pointing to a file or a directory . Creating links is a kind of

shortcuts to access a file. The two different types of links in UNIX are:

Soft Links or Symbolic Links

Hard links


Soft Links:

Soft Links can be created across file systems.

Soft link has a different inode number than the original file.

On deleting the original file, soft link cannot be accessed.

Soft link needs extra memory to store the original file name as its data.

Source file need not exist for soft link creation.

Can be created on a file or on a directory.

Access to the file is slower due to the overhead to access file.

Hard Links:

Hard links can be created only within the file system.

Hard links have the same inode number as the original file.

On deleting the original file, hard linked file can still be accessed.

Hard links do not need any extra data memory to save since it uses links

Source file should exist.

Can be created only on files, not on directories.

Access to the file is faster compared to soft link.

14) grep related interview questions ?

  • Checking for full words, not for sub-strings using grep -w

grep -iw "is" filename

  • Display N lines after match

grep -A 3 -i "example" filename

  • Display N lines before match

grep -B 2 "single WORD" filename

  • Display N lines around match

grep -C 2 "Example" filename

  • Searching in all files recursively using grep

grep -r "ramesh" *

  • Counting the number of matches using grep

grep -c "go" demo_text

  • Display only the file names which matches the given pattern using grep -l

grep -l this filename*


  • Show line number while displaying the output using grep -n

grep -n "go" filename

  • Count of empty lines ( ^$ )

grep -c "^$" filename

  • how to match more than one pattern

grep -e "a" -e "b" -e "c" filename

  • Count the empty line in a file

grep -c '^$' filename

15)grep and egrep differences ?

Grep

Unlike egrep in grep, ?, +, {, |, (, and ), are rather treated as pattern instead of meta characters. By putting ‘backslash’ in front of meta character can let the grep to treat it as meta characters like \?, \+, \{, \|, \(, and \).

ls | grep '.txt|.py'

Now just consider the above example, in this command we are listing down all the files in the present working directory. Using pipe we are giving the output of ls command to grep. The grep command will check if there is any file with .text|.py extension.

egrep

Now let’s see egrep side of the things. egrep is efficient and fast when it comes to searching for a regular expression pattern in large text files as it treats meta-characters as is and doesn’t substitute them as strings like in grep, and hence you are freed from the burden of escaping them exclusively as in grep.

ls | egrep '.txt|.py'

Now consider again the same example with egrep, here egrep will look for files with either .txt or .py extension. By using egrep we can even search for multiple pattern, files at a time using one command. We can make grep also do the same by escaping the characters but that’s an overhead for a power user since Linux command-line is all about reducing the amount of work to be done.

16) Linux file tree or file structure?

1. / – Root

Every single file and directory starts from the root directory.

Only root user has write privilege under this directory.

Please note that /root is root user’s home directory, which is not same as /.

2. /bin – User Binaries

Contains binary executables.

Common Linux commands you need to use in single-user modes are located under this directory.

Commands used by all the users of the system are located here.

For example: ps, ls, ping, grep, cp.

3. /sbin – System Binaries

Just like /bin, /sbin also contains binary executables.

But, the linux commands located under this directory are used typically by system aministrator, for system maintenance purpose.

For example: iptables, reboot, fdisk, ifconfig, swapon

4. /etc – Configuration Files

Contains configuration files required by all programs.

This also contains startup and shutdown shell scripts used to start/stop individual programs.

For example: /etc/resolv.conf, /etc/logrotate.conf

5. /dev – Device Files

Contains device files.

These include terminal devices, usb, or any device attached to the system.

For example: /dev/tty1, /dev/usbmon0

6. /proc – Process Information

Contains information about system process.

This is a pseudo filesystem contains information about running process. For example: /proc/{pid} directory contains information about the process with that particular pid.

This is a virtual filesystem with text information about system resources. For example: /proc/uptime

7. /var – Variable Files

var stands for variable files.

Content of the files that are expected to grow can be found under this directory.

This includes — system log files (/var/log); packages and database files (/var/lib); emails (/var/mail); print queues (/var/spool); lock files (/var/lock); temp files needed across reboots (/var/tmp);

8. /tmp – Temporary Files

Directory that contains temporary files created by system and users.

Files under this directory are deleted when system is rebooted.

9. /usr – User Programs

Contains binaries, libraries, documentation, and source-code for second level programs.

/usr/bin contains binary files for user programs. If you can’t find a user binary under /bin, look under /usr/bin. For example: at, awk, cc, less, scp

/usr/sbin contains binary files for system administrators. If you can’t find a system binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd, userdel

/usr/lib contains libraries for /usr/bin and /usr/sbin

/usr/local contains users programs that you install from source. For example, when you install apache from source, it goes under /usr/local/apache2

10. /home – Home Directories

Home directories for all users to store their personal files.

For example: /home/john, /home/nikita

11. /boot – Boot Loader Files

Contains boot loader related files.

Kernel initrd, vmlinux, grub files are located under /boot

For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic

12. /lib – System Libraries

Contains library files that supports the binaries located under /bin and /sbin

Library filenames are either ld* or lib*.so.*

For example: ld-2.11.1.so, libncurses.so.5.7

13. /opt – Optional add-on Applications

opt stands for optional.

Contains add-on applications from individual vendors.

add-on applications should be installed under either /opt/ or /opt/ sub-directory.

14. /mnt – Mount Directory

Temporary mount directory where sysadmins can mount filesystems.

15. /media – Removable Media Devices

Temporary mount directory for removable devices.

For examples, /media/cdrom for CD-ROM; /media/floppy for floppy drives; /media/cdrecorder for CD writer

16. /srv – Service Data

srv stands for service.

Contains server specific services related data.

For example, /srv/cvs contains CVS related data.


17)what is cronjob and crontab ?

The software utility cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.

Crontab Options

The following are the available options with crontab:

• crontab –e : Edit the crontab file. This will create a crontab, if it

doesn’t exist

• crontab –l : Display the crontab file.

• crontab -r : Remove the crontab file.

• crontab -ir : This will prompt user before deleting a crontab.

Description of Cron fields

Following is the format of the crontab file.

{minute} {hour} {day-of-month} {month} {day-of-week}

{full-path-to-shell-script}

• minute: Allowed range 0 – 59

• hour: Allowed range 0 – 23

• day-of-month: Allowed range 0 – 31

• month: Allowed range 1 – 12. 1 = January. 12 = December.

• Day-of-week: Allowed range 0 – 7. Sunday is either 0 or 7.

How to View Crontab Entries

crontab -l

How to Edit Crontab Entries

crontab -e

for different user

crontab -eu username ---> for this you have to be root priveleged

crontab -lu username –--> list the other user crontab

cd /var/spool/cron all user crontab

cd /etc/crontab

Two files of crontab command are:

  • cron.allow – It decides which users need to be permitted from using crontab command.

  • cron.deny – It decides which users need to be prevented from using crontab command.

18) Find command realted interview questions ?

Finding the Top 5 Big Files

find . -type f -exec ls -lrt {} \;|sort -nr -k 5|head -5 -->>>from myself

find . -type f -exec ls -s {} \; | sort -n -r | head -5

Finding the Top 5 Small Files

# find . -type f -exec ls -s {} \; | sort -| head -5
 
find . -not -empty -type f -exec ls -s {} \; | sort -| head -5
 

Following command will search for *.log files starting from / (root) and only in the current file system. i.e If you have multiple partitions mounted under / (root), the following command will NOT search all those mounted partitions.

# find / -xdev -name "*.log"

INVERT MATCH

find -maxdepth 1 -not -iname "MyCProgram.c"

Find Files Based on file-type using option -type

Find only the socket files.

# find . -type s

Find all directories

# find . -type d

Find only the normal files

# find . -type f

Find all the hidden files

# find . -type f -name ".*"

Find all empty files (zero byte file) in your home directory and its subdirectory

find ~ -empty

Find all the hidden directories

# find . -type d -name ".*"
 
# Find the passwd file under root and one level down. (i.e root — level 1, and one sub-directory — level 2)
 
find -maxdepth 2 -name passwd
 
# Find the passwd file under root and two levels down. (i.e root — level 1, and two sub-directories — level 2 and 3 )
 
   find / -maxdepth 3 -name passwd
 
 Remove big archive files using find command
 

find / -type f -name *.zip -size +100M -exec rm -i {} \;

Find files which are modified after modification of a particular FILE

find -newer /etc/passwd

above example displays all the files which are modified after the /etc/passwd files was modified. This is helpful, if you want to track all the activities you’ve done after adding a new user.

FIND

min argument treats its argument as minutes. For example, min 60 = 60 minutes (1 hour).

time argument treats its argument as 24 hours. For example, time 2 = 2*24 hours (2 days).

While doing the 24 hours calculation, the fractional parts are ignored so 25 hours is taken as 24 hours, and 47 hours is also taken as 24 hours, only 48 hours is taken as 48 hours. To get more clarity refer the -atime section of thefind command man page.

To find the files based up on the content modification time, the option -mmin, and -mtime is used. Following is the definition of mmin and mtime from man page.

-mmin n File’s data was last modified n minutes ago.

-mtime n File’s data was last modified n*24 hours ago

1. To find files modified in the last 5 days:

find . -mtime -5 2. To find files modified before 5 days:

find . -mtime +5

Note: Developers, be aware. + is not default in find. If you omit the '+', it has a different meaning. It means to find files modified exactly before 5 days.

3. To find files modified in the last 40mins:

find . -mmin -40

4. To find files modified before 40mins:

find . -mmin +40

The above commands will find both files and directories modifying the criteria. If you want to find only files, use the -type option.

find . -type f -mmin -40

This will find only the files modified in the last 40 mins, not directories.

5. By the way, not in all Unix flavours one will find the -mmin option. If you dont have the mmin option, use the following:

First create a dummy file whose timestamp is the time you are looking for

touch -d "40 mins ago" temp

The above touch command will create a temp file whose timstamp is 40mins before. For example, if the time now is 10hours 50mins, the temp file timstamp will be 10hours 40mins.

If your Unix flavor does not have the "-d" option in the touch command, you can use the following method to set the timestamp:

touch -t 1008211020 temp

This creates a temp file whose time stamp is 2010,Aug 21, 10hours 20mins. [YYMMDDHHMM]

Second, search files which are modified after this file temp has been modified. The below command will display all the files modified after the temp has been modified OR in other words find files which are newer than temp file:

find . -newer temp

Similarly, to find files which are modified before 40 mins. In other words to negate the above search, use the exclamation:

find . ! -newer temp

In the same way, we can find files modified from any time we need

6. One of the frequent requirement a sys admin gets is to find files modified before say last 2 days and 10 hours 30mins and move them to a backup directory. It can be achieved by the below commands:

touch -d "2days 10 hours 30 mins ago" temp find / -type f ! -newer temp -exec mv '{}' ~/backup \;

The above example does 2 things:

a. First create a temp file whose timstamp is 2 days 10 hours and 30mins ago.

b. Finds all the files under root which are older than the temp file and moves them to the backup directory.

The same thing using "touch -t" will be like assuming todays date is 21 Aug 2010, 15hours,45mins:

touch -t 1008190515 temp find / -type f ! -newer temp -exec mv '{}' ~/backup \;

1008190515 indicates 2010(10), Aug(08), 19th(19), 5 hours(05) and 15mins.

19) what is background job?

When you execute a UNIX shell-script or command that takes a long time, you can run it as a background job.

In this article, let us review how to execute a job in the background, bring a job to the foreground, view all background jobs, and kill a background job.

1. Executing a background job

Appending an ampersand ( & ) to the command runs the job in the background.

For example, when you execute a find command that might take a lot time to execute, you can put it in the background as shown below. Following example finds all the files under root file system that changed within the last 24 hours.

# find / -ctime -1 > /tmp/changed-file-list.txt &

2. Sending the current foreground job to the background using CTRL-Z and bg command

You can send an already running foreground job to background as explained below:

· Press ‘CTRL+Z’ which will suspend the current foreground job.

· Execute bg to make that command to execute in background.

For example, if you’ve forgot to execute a job in a background, you don’t need to kill the current job and start a new background job. Instead, suspend the current job and put it in the background as shown below.

# find / -ctime -1 > /tmp/changed-file-list.txt

# [CTRL-Z]

[2]+ Stopped find / -ctime -1 > /tmp/changed-file-list.txt

# bg

3. View all the background jobs using jobs command

You can list out the background jobs with the command jobs. Sample output of jobs command is

# jobs

[1] Running bash download-file.sh &

[2]- Running evolution &

[3]+ Done nautilus .

4. Taking a job from the background to the foreground using fg command

You can bring a background job to the foreground using fg command. When executed without arguments, it will take the most recent background job to the foreground.

# fg

If you have multiple background ground jobs, and would want to bring a certain job to the foreground, execute jobs command which will show the job id and command.

In the following example, fg %1 will bring the job#1 (i.e download-file.sh) to the foreground.

# jobs

[1] Running bash download-file.sh &

[2]- Running evolution &

[3]+ Done nautilus .

# fg %1

5. Kill a specific background job using kill %

If you want to kill a specific background job use, kill %job-number. For example, to kill the job 2 use

# kill %2


control-z

Stop (don't kill) the foreground job, and then return to the shell

Jobs

Check the status of jobs in the current session

Ps -u username

Check the status of processes, including those from other sessions. On BSD systems, use 'ps -gx'.

Kill -9 %1

Kill a job, by specifying its job number after the percent sign

Kill -9 123

Kill a process, by specifying its process id (PID) number

Bg

Run the most recently stopped job in the background

fg

Bring most recently backgrounded job to the foreground

Fg %1

Bring a job to foreground by specifying its job number after the percent sign

Putting a Job in Background:-

1. mozilla &

or

2. mozilla

^Z

bg

20) file parameters in Linux ?

$0 -The filename of the current script.

$n - 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 argument is $1, the second argument is $2, and so on).

$# - The number of arguments supplied to a script.

$* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.

$@ - All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.

$? - The exit status of the last command executed.

$$ - The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

$! - The process number of the last background command.

21) what is the difference between $@ and $* ?

The meaning of $* and $@ is identical when not quoted or when used as a parameter assignment value or as a file name. However, when used as a command argument, $* is equivalent to ``$1d$2d...'', where d is the first character of the IFS variable, whereas $@ is equivalent to $1 $2.

22)What is Sticky Bit?

Sticky Bit is mainly used on folders in order to avoid deletion of a folder and its content by other users though they having write permissions on the folder contents. If Sticky bit is enabled on a folder, the folder contents are deleted by only owner who created them and the root user. No one else can delete other users data in this folder(Where sticky bit is set). This is a security measure to avoid deletion of critical folders and their content(sub-folders and files), though other users have full permissions.

Sticky Bit can be set in two ways

1. Symbolic way (t,represents sticky bit)

2. Numerical/octal way (1, Sticky Bit bit as value 1)

Use chmod command to set Sticky Bit on Folder: /opt/dump/

Symbolic way:

chmod o+t /opt/dump/ or chmod +t /opt/dump/

Let me explain above command, We are setting Sticky Bit(+t) to folder /opt/dump by using chmod command.

Numerical way:

chmod 1757 /opt/dump/

Here in 1757, 1 indicates Sticky Bit set, 7 for full permissions for owner, 5 for read and execute permissions for group, and full permissions for others.

23) what is process in Linux?

A process refers to a program in execution; it’s a running instance of a program. It is made up of the program instruction, data read from files, other programs or input from a system user.

Types of Processes

There are fundamentally two types of processes in Linux:

  • Foreground processes (also referred to as interactive processes) – these are initialized and controlled through a terminal session. In other words, there has to be a user connected to the system to start such processes; they haven’t started automatically as part of the system functions/services.

  • Background processes (also referred to as non-interactive/automatic processes) – are processes not connected to a terminal; they don’t expect any user input.

To see all the process

ps -ef

To see all the process run by a particular user ps -u username u

Kill any user's all processes killall -u username

-u used to specify user name, and u at the end of the command shows you complete path of the command executed.


24) what is tar and untar in Linux?

Creating an uncompressed tar archive using option cvf

tar cvf archive_name.tar dirname/

In the above command:

· c – create a new archive

· v – Verbosely list files which are processed.

· f – following is the archive file name

Creating a tar gzipped archive using option cvzf

Tar cvzf archive_name.tar.gz dirname/

Note: .tgz is same as .tar.gz

Extracting (untar) an archive using tar command

Tar xvf archive_name.tar

Extract a gzipped tar archive ( *.tar.gz ) using option xvzf

Tar xvfz archive_name.tar.gz

Listing an archive using tar command

View the tar archive file content without extracting using option tvf

tar tvf archive_name.tar

View the *.tar.gz file content without extracting using option tvzf

Tar tvfz archive_name.tar.gz

Adding a file or directory to an existing archive using option -r

Tar rvf archive_name.tar newfile

Note: You cannot add file or directory to a compressed archive. If you try to do so, you will get “tar: Cannot update compressed archives” error as shown below.

Estimate the tar archive size

The following command, estimates the tar file size ( in KB ) before you create the tar file.

$ tar -cf - /directory/to/archive/ | wc -c

20480

Estimate the file size of an archive of the directory directory/to/archive, but do not create the file. Here, the archive file is specified as a dash ("-"), which tells tar to send its archived output to the standard output rather than a file on disk. This output is then piped to the wc command, which reports how many bytes (-c) were in the input it received.

How to open an archived file (i.e *.tar)

less autocorrect.tar

-rwxrwxrwx anthony/anthony 84149 2009-02-02 03:20 autocorrect.dat

-rwxrwxrwx anthony/anthony 443 2009-02-02 03:21 generator.rb

-rwxrwxrwx anthony/anthony 181712 2009-02-02 03:21 autocorrect.vim

How to open an archived, compressed file in gzip format (i.e *.tar.gz format)

less XML-Parser-2.36.tar.gz

drwxr-xr-x matt/matt 0 2007-11-20 19:58 XML-Parser-2.36/

-rw-r--r-- matt/matt 25252 2007-11-20 19:52 XML-Parser-2.36/Changes

drwxr-xr-x matt/matt 0 2007-11-20 19:58 XML-Parser-2.36/Expat/

-rw-r--r-- matt/matt 3184 2003-07-27 16:37 XML-Parser-2.36/Expat/encoding.h

How do I extract tar.gz files to a specific directory?

# tar xvfz /tmp/my_home_directory.tar.gz –C /home/ramesh

Add the file documents/work/budget.doc to the existing archive archive.tar. The r option is the same as the long option --append.

tar -rvf archive.tar documents/work/budget.doc

Add the file documents/work/budget.doc to the archive archive.tar only if it is newer than the version already in the archive (or does not yet exist in the archive). Here, u is the same as the long option --update.

tar -uvf archive.tar documents/work/budget.doc

Untar Single file from tar File

To extract a single file called cleanfiles.sh from cleanfiles.sh.tar use the following command. # tar -xvf cleanfiles.sh.tar cleanfiles.sh

25) how to print only uniq lines of the file ?

cat test

aa

aa

bb

bb

bb

xx

uniq test

aa

bb

xx

Count Number of Occurrences using -c option

uniq -c test

2 aa

3 bb

1 xx

Print only Duplicate Lines using -d option

uniq -d test

aa

bb

Print only duplicates line

uniq -D test

aa

aa

bb

bb

bb

Print only Unique Lines using -u option

uniq -u test

xx

26) how to check when machine is rebooted ?

$ uptime

20:52:01 up 137 days, 6:13, 1 user, load average: 0.00, 0.00, 0.00

$ last reboot

reboot system boot 2.6.32-48-generi Tue Jul 2 11:21 - 12:42 (01:20)

reboot system boot 2.6.32-48-generi Mon Jul 1 23:51 - 02:32 (02:41)

reboot system boot 2.6.32-48-generi Mon Jul 1 18:40 - 22:07 (03:27)

reboot system boot 2.6.32-48-generi Mon Jul 1 13:48 - 16:20 (02:32)

reboot system boot 2.6.32-48-generi Mon Jul 1 11:28 - 12:07 (00:38)

$ who -b

system boot 2013-07-02 11:21

$ last -x|grep reboot

reboot system boot 2.6.32-48-generi Tue Jul 2 11:21 - 12:48 (01:26)

reboot system boot 2.6.32-48-generi Mon Jul 1 23:51 - 02:32 (02:41)

reboot system boot 2.6.32-48-generi Mon Jul 1 18:40 - 22:07 (03:27)

reboot system boot 2.6.32-48-generi Mon Jul 1 13:48 - 16:20 (02:32)

reboot system boot 2.6.32-48-generi Mon Jul 1 11:28 - 12:07 (00:38)

$ last -x|grep shutdown

shutdown system down 2.6.32-48-generi Tue Jul 2 02:32 - 11:21 (08:48)

shutdown system down 2.6.32-48-generi Mon Jul 1 22:07 - 23:51 (01:43)

shutdown system down 2.6.32-48-generi Mon Jul 1 16:20 - 18:40 (02:19)

shutdown system down 2.6.32-48-generi Mon Jul 1 12:07 - 13:48 (01:40)

shutdown system down 2.6.32-48-generi Mon Jul 1 12:07 - 12:07 (00:00)

shutdown system down 2.6.32-48-generi Mon Jul 1 09:34 - 11:28 (01:54

27) what is difference between less and more?

Less is a full-screen application that gives you a search able, scrollable window and clears the screen after you exit, less can also be backgrounded and restored like other full screen terminal applications. less also has a command to open the currently viewed file in your default editor.

More just prints the text as is, stopping for page breaks, and does not clear the screen, it can be backgrounded but it doesn't clear the screen. More also only reads in the file as it displays where less may read the file into memory first. Each handles line wrapping differently which gives different results when selecting and pasting text.

both tools full fill the same function but they do it in different ways, so you can pick whichever one you want for the situation at hand

---

As you know "less" and "more" both allow you to view a file, however "less" has some advantages. The main advantage of using "less" is that you can reverse scroll through a file and you don't need to wait for "less" to load the whole file into memory before you can start to view it. --- 28)Awk command in Linux ?

Awkk file 100 Thomas Manager Sales 5,000 200 Jason Developer Technology 5,500 300 Sanjay Sysadmin Technology 7,000 400 Nisha Manager Marketing 9,500 500 Randy DBA Technology 6,000 /hymn/beta/unixx$ awk '$4 ~/Technology/{print}' awkk 200 Jason Developer Technology 5,500 300 Sanjay Sysadmin Technology 7,000 500 Randy DBA Technology 6,000 /hymn/beta/unixx$ awk '$4 ~/Technology/' awkk 200 Jason Developer Technology 5,500 300 Sanjay Sysadmin Technology 7,000 500 Randy DBA Technology 6,000 /hymn/beta/unixx$ awk '/Technology/' awkk 200 Jason Developer Technology 5,500 300 Sanjay Sysadmin Technology 7,000 500 Randy DBA Technology 6,000 pankaj@pankaj:/hymn/beta/unixx$ /hymn/beta/unixx$ awk '$4 ~/Technology/{print $1,$2}' awkk 200 Jason 300 Sanjay 500 Randy /hymn/beta/unixx$ awk '$1 == "200" || $4 == "Technology"' awkk 200 Jason Developer Technology 5,500 300 Sanjay Sysadmin Technology 7,000 500 Randy DBA Technology 6,000 /hymn/beta/unixx$ awk '$1 == "200" && $4 == "Technology"' awkk 200 Jason Developer Technology 5,500 /hymn/beta/unixx$ hymn/beta/unixx$ awk '$1 == "200" && $4 == "Technology"{print}' awkk 200 Jason Developer Technology 5,500 /hymn/beta/unixx$ awk '$1 == "200" && $4 == "Technology"{print $1,$2}' awkk 200 Jason hymn/beta/unixx$ awk '$1 ~ 200 && $4 ~/Technology/{print $1,$2}' awkk 200 Jason :/hymn/beta/unixx$ awk '$1>200' awkk 300 Sanjay Sysadmin Technology 7,000 400 Nisha Manager Marketing 9,500 500 Randy DBA Technology 6,000 NEW FILE 100|Thomas|Manager|Sales|5,000 200|Jason|Developer|Technology|5,500 300|Sanjay|Sysadmin|Technology|7,000 400|Nisha|Manager|Marketing|9,500 500|Randy|DBA|Technology|6,000 :/hymn/beta/unixx$ awk '{print $1 ,$2}' awk1 100|Thomas|Manager|Sales|5,000 200|Jason|Developer|Technology|5,500 300|Sanjay|Sysadmin|Technology|7,000 400|Nisha|Manager|Marketing|9,500 500|Randy|DBA|Technology|6,000 hymn/beta/unixx$ awk -F"|" '{print $1 ,$NF}' awk1 100 5,000 200 5,500 300 7,000 400 9,500 500 6,000 NF → indicates the last field.

29) vi editor in Linux ?

VI EDITOR

:set nu, :set number, :set nonu, :set nonumber

Navigation

h → left

j → down

k → up

l → right

1G → move to beginning of a file

10G → move to line 10

G → move to end of the file

ctrl+g → display current line number and percentage of file

0 → move the cursor beginning of the current line

$ -->move the cursor end of the current line

Inserting Text

o → open line below

O → open line above

Deleting and moving Text

x → delete character under cursor

6x → delete character under cursor and five characters on right

X → Delete previous character

dd → delete current line

4dd → delete four lines

dw → delete word

d0(d & Zero) → delete to beginning of line.

d$ → delete to end of line

J → Join current line with next line

u → undo the effect of the last command

~ → change the character at the cursor position lower to upper or vice versa.

Copying Text

yy → copy current line

6yy → copy six lines

yw → copy word-match

p → put copy text on right or below

P → put copy text on left or above

:nd → delete nth line

:m,nd → delete line m to n.

:n mo p → moves line n after line p

:m,n mo p → moves lines m to n after line p

:m co p → copies line m after line p

:m,n co p → copies lines m to n after line p

:m,n w fname → writes lines m to n to a file fname.

:m,n >> fname → appends lines m to n to a file fname.

:r fname → read the content of a file fname at current cursor position.

:r !cmd –> execute shell command and output of the command read at current cursor position.

:n1,n2w fname → write lines n1 to n2 to file fname

:n1,n2w >> fname → append lines n1 to n2 to file fname

:$w fname→ right last line to file fname

:e fname → stop editing current file and edit file fname.

:e! fname → as above, but after abandoning changes made to current file

:e! → load last saved version of current file

ctrl+^ → return to most recently edited current file.

:n → edit next file (when vi is invoked with multiple filenames)

:r fname → insert content of file fname below current line.

Search & repeat

/pat → cursor is on the matched word( search forward)

:/pat → cursor on the beginning of the matched word line.( search forward)

?pat → search backward

n → repeat search in same direction of previous search

N → repeat search in opposite direction of previous search

Substitution:-

:.s/s1/s2/ → replace first occurrence of s1 with s2 in current line

:1,$s/s1/s2/ → replace first occurrence of s1 with s2 in entire file

:1,$s/s1/s2/g → globally replace s1 with s2

:1,$s/#//g → globally remove #

:3,10s/^/#/ → insert a # at beginning of line 3 to 10

:s/$/;/ → insert ; at the end of the last line

:g/^$/d → delete blank lines in a file

:2,4d → delete line number 2 to 4

Interface to UNIX

The editor can be suspended with ctrl+z only for those shells that enable job control.

:!cmd → run unix command cmd

:!% → execute current file as a shell or perl script

:r !cmd → insert output of the command cmd below current line.

Loading a multiple files:-

vi file1 file2 file3

:n → permits editing the next file in buffer

:n! → permits editing the next file without saving the current file.

:rew → permits editing the first file of a buffer

:rew! -->permits editing the first file of a buffer without saving the current file.

:args → display the names of all files in the buffer in which name of the current file is enclosed within [].

:f → displays the name of the current file.

30)Is it possible to substitute ‘ls’ command with ‘echo’ command?

Echo * == ls


31)Which command is used to identify the types of file?

The ‘file’ command is used to identify the types of file. The syntax is ‘file [option] File_name

/hymn/beta/unixx$ file sedd

sedd: ASCII English text

pankaj@pankaj:/hymn/beta/unixx$ file fore1.sh

fore1.sh: ASCII text

32)You have a file (say file1.txt). You want this file to be alter-proof so that no one can edit or delete this file, not even root. What will you do?

The Syntax of command chattr, for the above purpose is:

chattr +i file1.txt

Now try to remove the file using normal user.

rm -r file1.txt

rm: remove write-protected regular empty file ` file1.txt'? Y

rm: cannot remove ` file1.txt': Operation not permitted

Now try to remove the file using root user.

rm -r file1.txt


cannot remove ` file1.txt': Operation not permitted

33)What is swapping and paging?

UNIX based operating systems automatically handle swapping and paging. Swapping and paging are processes that occur when the operating system is managing system memory. Every process in UNIX based systems has individual segments. An area of the disk is treated as the swap space where these segments are stored temporarily as long as a process needs them. This is done to conserve memory, because multiple processes are usually occurring at once and there isn’t enough physical memory to store all of them.

Consider a reference book, for example. You only open the page you need- you don’t need to have all the pages open at once. That is both almost impossible and extremely inefficient. A book is comparable to a process in UNIX. At any given time, there are several books that UNIX is reading. However, UNIX only takes a few pages from a book at one time, as needed. Once it is done with the page, or if it becomes “old”, it is sent back to storage. This is known as paging. Sometimes UNIX sends the entire book, with all its pages, back to the memory- this is known as swapping. This happens when the work load is really heavy.

Paging is more efficient if UNIX is running a large number of processes at one time. Pages (memory segments) can be stored and retrieved as needed. Swapping is more demanding in terms of resources and memory, but it provides faster results, as UNIX doesn’t need to search and retrieve pages every single time while it is executing a process.


34)Your application home directory is full? How will you find which directory is taking how much space?

By using disk usage (DU) command in Unix for example du –sh . | grep G will list down all the directory which has GIGS in Size.


35)what is file permission in Linux?

Just to add one more point, how the numbers 4,2 and 1 derived resepctively for read write execute. In the 3×3 structure ( 101 101 101), the first three bits are for users. If its 111, then it indicates, user(owner) has all bits enabled on the file/folder. 1 at the first position indicates read, the next 1 for write, then the last one for execute. So if the user(owner) needs ONLY read access to a file, then it will be 100. If you convert the binary100 to it corresponding decimal it will be 1*2^2 + 0*2^1 + 0*2^1 = 4. Similarly if ONLY need write permission then 010, which will be ( 0*2^2 + 1*2^1 + 0*2^0 = 2) number two(2) in decimal system. For read write combination on a file it will be turning on the corresponding bits, ie 110 = ( 1*2^2 + 1*2^1 + 0*2^0 = 6) decimal number 6.

Three file permissions:

§ read: permitted to read the contents of file.

§ write: permitted to write to the file.

§ execute: permitted to execute the file as a program/script.

Three directory permissions:

§ read: permitted to read the contents of directory ( view files and sub-directories in that directory ).

§ write: permitted to write in to the directory. ( create files and sub-directories in that directory )

§ execute: permitted to enter into that directory.

Umask

022 is Responsible for the default permission of a file

The default umask value is 0022, which decides the default permission for a new file or directory. Default permission for a directory is 0777, for files the permissions are 0666 from which the default umask value 0022 is deducted to get the newly created files or directory permission.

Final default permission for a file is calculated as shown below:

§ Default file permission: 666

§ Default umask : 022

§ Final default file permission: 644

Final default permission for a directory is calculated as shown below:

§ Default directory permission: 777

§ Default umask: 022

§ Final default directory permission: 755

You can change the umask value to appropriate value of what you need based upon the above calculation. For example, if you don’t want anybody other than the user (owner) to do anything on the file or directory then you can give umask as 0077.


36)What is the difference between mtime, atime and ctime ?

mtime, atime and ctime are timestamps associated with the modification, access and change of any file respectively.


mtime

mtime (modification time) indicates the time the contents of the file has been changed. Mind you, only the contents. Not the attributes. For instance, if you open a file and change some (or all) of its content, its mtime gets updated. If you change a file's attribute (like read-write permissions, metadata), its mtime doesn't change, but ctime will.


atime

atime (access time) is the timestamp that indicates the time that a file has been accessed. The file may have been opened by you, or may have been accessed by some other program or a remote machine. Anytime a file has been accessed, its access time changes.


ctime

ctime (change time) is the timestamp of a file that indicates the time that it was changed. Now, the modification can be in terms of its content or in terms of its attributes. Whenever anything about a file changes (except its access time), its ctime changes.


37) what is nohup ?

Using the ampersand (&) will run the command in a child process (child to the current bash session). However, when you exit the session, all child processes will be killed. Using nohup + ampersand (&) will do the same thing, except that when the session ends, the parent of the child process will be changed to "1" which is the "init" process, thus preserving the child from being killed.

Most of the time we login to remote server using ssh. If you start a shell script and you logout then the process is killed. Nohup helps to continue running the script in background even after you log out from shell.

Nohup command name &
eg: nohup sh script.sh &

Nohup catches the HUP signals. Nohup doesn't put the job automatically in the background. We need to tell that explicitly using &

38) what is NICE?

Nice command will launch a process with an user defined scheduling priority. Renice command will modify the scheduling priority of a running process.

Linux Kernel schedules the process and allocates CPU time accordingly for each of them. But, when one of your process requires higher priority to get more CPU time, you can use nice and renice command as explained in this tutorial. The process scheduling priority range is from -20 to 19. We call this as nice value.

A nice value of -20 represents highest priority and a nice value of 19 represent least priority for a process.

By default when a process starts, it gets the default priority of 0.

Launch a Program with Less Priority

Instead of launching the program with the default priority, you can use nice command to launch the process with a specific priority.

In this example, test.pl is launched with a nice value of 10.

$ nice -10 perl test.pl

Note: Remember that -10 in the above command sets the priority of a process to 10. The – in nice command stands for the hypen, which we use to pass options to the command.

So, to pass nice value of 5, you’ll say -5. To pass nice value of 6, you’ll say -6.

As you see below, this program is now launched with a nice value of 10, which means this will run at a lower priority when compared to other programs that are launched by default.

39) What is Zombie Process?

It is a process whose execution is completed but even the information exists in the process table. It occurs for the child process because the parent process needs to read the child process status. Once it is completed using the wait system call, then the zombie process is removed from the process table. This is known as Zombie Process.Process status of zombie process in process table is Z.

40)What is env command in Linux?

Ans: env command allows users to set or print the environment variables. During troubleshooting, users can find it useful for checking if the wrong environment variable prevents your application from starting.

env Command Example :

$ env
PYTHON_PIP_VERSION=9.0.1
HOME=/root
DB_NAME=test
PATH=/usr/local/bin:/usr/local/sbin
LANG=C.UTF-8
PYTHON_VERSION=3.4.6
PWD=/
DB_URI=mongodb://database:27017/test

40)What is the difference between cmp and diff commands?

cmp

-Byte by byte comparision performed for two files comparision and displays the first mismatch byte.

-cmp returns the 1st byte and the line no of the fileone to make the changes to make the fileone identical to filetwo.

-Directory names can not be used.

diff

-Indicates the changes that are to be done to make the files identical.

-returns the text of filetwo that is different from filetwo.

-Directory names can be used


41) What is df and du command in Linux?

Users can use df command to troubleshoot disk space issues. Here df stands for display free disk space and h is human readable.

df Command Example:

df -h

du command in Linux is used to retrieve more detailed information about which files use the disk space in a directory.

du Command Example:

$ du -sh /var/log/*
1.8M  /var/log/anaconda
384K  /var/log/audit
4.0K  /var/log/boot.log
0 /var/log/chrony
4.0K  /var/log/cron
4.0K  /var/log/maillog
64K /var/log/messages

42) How will you append one file to another in Linux?

The command:

cat file1 > file2

appends two files in Linux. You can append as many files using the command. For example, to append three files, named file1, file2, and file3, we can use the command:

cat file1 > file2 > file3

Another way of appending one file to another in Linux is by using the command:

cat file2>>file1

The >> operator appends the output of the named files.

43) How will you setup Password Aging in Linux?

The chage command allows the system administrators in Linux to enforce password aging. The command is used to change the number of days between mandatory password resets. The /etc/login.defs file is responsible for handling system-wide configuration. It can be edited for:

  • PASS_MAX_DAYS – Defines the maximum number of days a password may be used.

  • PASS_MIN_DAYS – Defines the minimum number of days allowed between password changes.

  • PASS_WARN_AGE – Defines the number of days warning is given before a password expires.

44) How to lock user account in Linux?

Locking user account is done for the security purpose so that unauthorized users cannot login. So, we have a few ways to lock the user account. Some of them are below.

  1. Lock or disable the password using passwd command.

  2. Expire the user account using usermod command or chage command.

  3. Changing the shell using nologin command ( /sbin/nologin ).


45) Explain the terms suid, sgid and sticky bit?

In addition to the basic file permissions in Linux, there are few special permissions that are available for executable files and directories.

SUID: If setuid bit is set, when the file is executed by a user, the process will have the same rights as the owner of the file being executed.

SGID: Same as above, but inherits group privileges of the file on execution, not user privileges. Similar way when you create a file within the directory, it will inherit the group ownership of the directories.

Sticky bit: sticky bit was used on executables in linux so that they would remain in the memory more time after the initial execution, hoping they would be needed in the near future. But mainly it is on folders, to imply that a file or folder created inside a stickybit enabled folder could only be deleted by the owner. A very good implementation of sticky bit is /tmp , where every user has write permission but only users who own a file can delete them.


46) What use of /etc/passwd and /etc/shadow file?

The /etc/shadow stores actual password in an encrypted format with some additional properties related to user password. It mainly holds the account aging parameters. All fields are separated by a colon (:) symbol. It contains one entry per line for each user listed in /etc/passwd file.


47)Predict the output of below code?


 Main()
 {
 Fork(); Fork(); Fork();
 Printf("hello World!");
 }

"Hello World" will be printed 8 times.

Explanation:

2^n times where n is the number of calls to fork().


48)What are the Orphan Processes?

An Orphan Process is a process whose parent is dead (terminated). A process with dead parents is adopted by the init process. When does a process become an orphan process? Sometimes, when a process crashes, it leaves the children processes alive, transforming them into orphan processes. A user can also create a orphan process, by detaching it from the terminal.

How to find orphaned processes: This command will not display only the orphaned processes, but all the processes having the PPID 1 (having the init process as it’s parent).

$ ps -elf | awk '{if ($5 == 1){print $4" "$5" "$15}}'
 298 1 upstart-udev-bridge
 302 1 udevd
 438 1 /usr/sbin/sshd
 [...]

Orphan processes use a lot of resources, so they can be easily found with top or htop. To kill an orphaned process, use kill -9 PID.


49)What are Loops and explain three different methods of loops in brief?Loops are the ones, which involve repeating some portion of the program/script either a specified number of times or until a particular condition is being satisfied.

3 methods of loops are:

  • For Loop: This is the most commonly used loop. For loop allows specifying a list of values that the control variable in the loop can take. The loop is then executed for each value mentioned in the list.

  • While Loop: This is used in a program when we want to do something for a fixed number of times. While loop gets executed until it returns a zero value.

  • Until Loop: This is similar to while loop except that the loop executes until the condition is true. Until the loop gets executed at least once, it returns a non-zero value.

50)What is Shebang in a shell script?

Shebang is a # sign followed by an exclamation i.e. !. Generally, this can be seen at the beginning or top of the script/program. Usually, a developer uses this to avoid repetitive work. Shebang mainly determines the location of the engine which is to be used in order to execute the script.

Here ‘#’ symbol is called hash and ‘!’ is called a bang.

Example: #!/bin/bash

The above line also tells which shell to use.


51) if a file has 2000 lines so you want it to divide in 500 lines and make 4 files?


spilt -l500 filename

499 views0 comments

Recent Posts

See All
 

Subscribe Form

©2020 by Linux Advise