Monday, September 3, 2012


 Linux Interview Questions and Answers

You need to see the last fifteen lines of the files dog, cat and horse. What
command should you use?
tail -15 dog cat horse

The tail utility displays the end of a file. The -15 tells tail to display the last fifteen
lines of each specified file.

Who owns the data dictionary?
The SYS user owns the data dictionary. The SYS and SYSTEM users are created
when the database is created.

You routinely compress old log files. You now need to examine a log from two
months ago. In order to view its contents without first having to decompress
it, use the _________ utility.
zcat

The zcat utility allows you to examine the contents of a compressed file much the
same way that cat displays a file.

You suspect that you have two commands with the same name as the
command is not producing the expected results. What command can you use
to determine the location of the command being run?
which

The which command searches your path until it finds a command that matches the
command you are looking for and displays its full path.

You locate a command in the /bin directory but do not know what it does.
What command can you use to determine its purpose.
whatis

The whatis command displays a summary line from the man page for the specified
command.

You wish to create a link to the /data directory in bob's home directory so you
issue the command ln /data /home/bob/datalink but the command fails. What
option should you use in this command line to be successful.
Use the -F option

In order to create a link to a directory you must use the -F option.

When you issue the command ls -l, the first character of the resulting display
represents the file's ___________.
type

The first character of the permission block designates the type of file that is being
displayed.

What utility can you use to show a dynamic listing of running processes?
__________
top

The top utility shows a listing of all running processes that is dynamically updated.

Where is standard output usually directed?
to the screen or display

By default, your shell directs standard output to your screen or display.

You wish to restore the file memo.ben which was backed up in the tarfile
MyBackup.tar. What command should you type?
tar xf MyBackup.tar memo.ben

This command uses the x switch to extract a file. Here the file memo.ben will be
restored from the tarfile MyBackup.tar.

You need to view the contents of the tarfile called MyBackup.tar. What
command would you use?
tar tf MyBackup.tar

The t switch tells tar to display the contents and the f modifier specifies which file
to examine.

You want to create a compressed backup of the users' home directories. What
utility should you use?
tar

You can use the z modifier with tar to compress your archive at the same time as
creating it.

What daemon is responsible for tracking events on your system?
syslogd

The syslogd daemon is responsible for tracking system information and saving it to
specified log files.

You have a file called phonenos that is almost 4,000 lines long. What text filter
can you use to split it into four pieces each 1,000 lines long?

split

The split text filter will divide files into equally sized pieces. The default length of
each piece is 1,000 lines.

You would like to temporarily change your command line editor to be vi.
What command should you type to change it?
set -o vi

The set command is used to assign environment variables. In this case, you are
instructing your shell to assign vi as your command line editor. However, once
you log off and log back in you will return to the previously defined command line
editor.

What account is created when you install Linux?
root

Whenever you install Linux, only one user account is created. This is the superuser
account also known as root.

What command should you use to check the number of files and disk space
used and each user's defined quotas?

repquota

The repquota command is used to get a report on the status of the quotas you have
set including the amount of allocated space and amount of used space.

In order to run fsck on the root partition, the root partition must be mounted
as
readonly

You cannot run fsck on a partition that is mounted as read-write.

In order to improve your system's security you decide to implement shadow
passwords. What command should you use?
pwconv

The pwconv command creates the file /etc/shadow and changes all passwords to 'x'
in the /etc/passwd file.

Bob Armstrong, who has a username of boba, calls to tell you he forgot his
password. What command should you use to reset his command?
passwd boba

The passwd command is used to change your password. If you do not specify a
username, your password will be changed.

The top utility can be used to change the priority of a running process?
Another utility that can also be used to change priority is ___________?
nice

Both the top and nice utilities provide the capability to change the priority of a
running process.

What command should you type to see all the files with an extension of 'mem'
listed in reverse alphabetical order in the /home/ben/memos directory.
ls -r /home/ben/memos/*.mem

The -c option used with ls results in the files being listed in chronological order.
You can use wildcards with the ls command to specify a pattern of filenames.

What file defines the levels of messages written to system log files?
kernel.h

To determine the various levels of messages that are defined on your system,
examine the kernel.h file.

What command is used to remove the password assigned to a group?
gpasswd -r

The gpasswd command is used to change the password assigned to a group. Use
the -r option to remove the password from the group.

What command would you type to use the cpio to create a backup called
backup.cpio of all the users' home directories?
find /home | cpio -o > backup.cpio

The find command is used to create a list of the files and directories contained in
home. This list is then piped to the cpio utility as a list of files to include and the
output is saved to a file called backup.cpio.

What can you type at a command line to determine which shell you are using?

echo $SHELL

The name and path to the shell you are using is saved to the SHELL environment
variable. You can then use the echo command to print out the value of any variable
by preceding the variable's name with $. Therefore, typing echo $SHELL will
display the name of your shell.

What type of local file server can you use to provide the distribution
installation materials to the new machine during a network installation?
A) Inetd
B) FSSTND
C) DNS
D) NNTP
E) NFS
E - You can use an NFS server to provide the distribution installation materials
to the machine on which you are performing the installation. Answers a, b, c, and
d are all valid items but none of them are file servers. Inetd is the superdaemon
which controls all intermittently used network services. The FSSTND is the Linux
File System Standard. DNS provides domain name resolution, and NNTP is the
transfer protocol for usenet news.

If you type the command cat dog & > cat what would you see on your display?
Choose one:
a. Any error messages only.
b. The contents of the file dog.
c. The contents of the file dog and any error messages.
d. Nothing as all output is saved to the file cat.

d

When you use & > for redirection, it redirects both the standard output and
standard error. The output would be saved to the file cat.

You are covering for another system administrator and one of the users asks
you to restore a file for him. You locate the correct tarfile by checking the
backup log but do not know how the directory structure was stored. What
command can you use to determine this?
Choose one:
a. tar fx tarfile dirname
b. tar tvf tarfile filename
c. tar ctf tarfile
d. tar tvf tarfile

d

The t switch will list the files contained in the tarfile. Using the v modifier will
display the stored directory structure.

You have the /var directory on its own partition. You have run out of space.
What should you do? Choose one:
a. Reconfigure your system to not write to the log files.
b. Use fips to enlarge the partition.
c. Delete all the log files.
d. Delete the partition and recreate it with a larger size.

d

The only way to enlarge a partition is to delete it and recreate it. You will then
have to restore the necessary files from backup.

You have a new application on a CD-ROM that you wish to install. What
should your first step be?
Choose one:
a. Read the installation instructions on the CD-ROM.
b. Use the mount command to mount your CD-ROM as read-write.
c. Use the umount command to access your CD-ROM.
d. Use the mount command to mount your CD-ROM as read-only.

d

Before you can read any of the files contained on the CD-ROM, you must first
mount the CD-ROM.

When you create a new partition, you need to designate its size by defining the
starting and ending _____________.
cylinders

When creating a new partition you must first specify its starting cylinder. You can
then either specify its size or the ending cylinder.

What key combination can you press to suspend a running job and place it in
the background?

ctrl-z

Using ctrl-z will suspend a job and put it in the background.

The easiest, most basic form of backing up a file is to _____ it to another
location.
copy

The easiest most basic form of backing up a file is to make a copy of that file to
another location such as a floppy disk.

What type of server is used to remotely assign IP addresses to machines
during the installation process?
A) SMB
B) NFS
C) DHCP
D) FT
E) HTTP

C - You can use a DHCP server to assign IP addresses to individual machines
during the installation process. Answers a, b, d, and e list legitimate Linux servers,
but these servers do not provide IP addresses. The SMB, or Samba, tool is used for
file and print sharing across multi-OS networks. An NFS server is for file sharing
across Linux net-works. FTP is a file storage server that allows people to browse
and retrieve information by logging in to it, and HTTP is for the Web.

Which password package should you install to ensure that the central
password file couldn't be stolen easily?
A) PAM
B) tcp_wrappers
C) shadow
D) securepass
E) ssh

C - The shadow password package moves the central password file to a more
secure location. Answers a, b, and e all point to valid packages, but none of these
places the password file in a more secure location. Answer d points to an invalid
package.

When using useradd to create a new user account, which of the following
tasks is not done automatically.
Choose one:

a. Assign a UID.
b. Assign a default shell.
c. Create the user's home directory.
d. Define the user's home directory.

c

The useradd command will use the system default for the user's home directory.
The home directory is not created, however, unless you use the -m option.

You want to enter a series of commands from the command-line. What would
be the quickest way to do this?
Choose One
a. Press enter after entering each command and its arguments
b. Put them in a script and execute the script
c. Separate each command with a semi-colon (;) and press enter after the last
command
d. Separate each command with a / and press enter after the last command

c

The semi-colon may be used to tell the shell that you are entering multiple
commands that should be executed serially. If these were commands that you
would frequently want to run, then a script might be more efficient. However, to
run these commands only once, enter the commands directly at the command line.

You attempt to use shadow passwords but are unsuccessful. What
characteristic of the /etc/passwd file may cause this?
Choose one:
a. The login command is missing.
b. The username is too long.
c. The password field is blank.
d. The password field is prefaced by an asterisk.

c

The password field must not be blank before converting to shadow passwords.

When you install a new application, documentation on that application is also
usually installed. Where would you look for the documentation after installing
an application called MyApp?
Choose one:

a. /usr/MyApp
b. /lib/doc/MyApp
c. /usr/doc/MyApp
d. In the same directory where the application is installed.

c

The default location for application documentation is in a directory named for the
application in the /usr/doc directory.

What file would you edit in your home directory to change which window
manager you want to use?
A) Xinit
B) .xinitrc
C) XF86Setup
D) xstart
E) xf86init

Answer: B - The ~/.xinitrc file allows you to set which window man-ager you want
to use when logging in to X from that account.
Answers a, d, and e are all invalid files. Answer c is the main X server
configuration file.

What command allows you to set a processor-intensive job to use less CPU
time?
A) ps
B) nice
C) chps
D) less
E) more

Answer: B - The nice command is used to change a job's priority level, so that it
runs slower or faster. Answers a, d, and e are valid commands but are not used to
change process information. Answer c is an invalid command.

While logged on as a regular user, your boss calls up and wants you to create
a new user account immediately. How can you do this without first having to
close your work, log off and logon as root?
Choose one:
a. Issue the command rootlog.
b. Issue the command su and type exit when finished.
c. Issue the command su and type logoff when finished.

d. Issue the command logon root and type exit when finished.

Answer: b
You can use the su command to imitate any user including root. You will be
prompted for the password for the root account. Once you have provided it you are
logged in as root and can do any administrative duties.

There are seven fields in the /etc/passwd file. Which of the following lists all
the fields in the correct order?
Choose one:
a. username, UID, GID, home directory, command, comment
b. username, UID, GID, comment, home directory, command
c. UID, username, GID, home directory, comment, command
d. username, UID, group name, GID, home directory, comment
Answer: b
The seven fields required for each line in the /etc/passwd file are username, UID,
GID, comment, home directory, command. Each of these fields must be separated
by a colon even if they are empty.

Which of the following commands will show a list of the files in your home
directory including hidden files and the contents of all subdirectories?
Choose one:
a. ls -c home
b. ls -aR /home/username
c. ls -aF /home/username
d. ls -l /home/username

Answer: b
The ls command is used to display a listing of files. The -a option will cause
hidden files to be displayed as well. The -R option causes ls to recurse down the
directory tree. All of this starts at your home directory.

In order to prevent a user from logging in, you can add a(n) ________at the
beginning of the password field.
Answer: asterick

If you add an asterick at the beginning of the password field in the /etc/passwd file,
that user will not be able to log in.

You have a directory called /home/ben/memos and want to move it to /home/
bob/memos so you issue the command mv /home/ben/memos /home/bob. What
is the results of this action?
Choose one:
a. The files contained in /home/ben/memos are moved to the directory /home/
bob/memos/memos.
b. The files contained in /home/ben/memos are moved to the directory /home/
bob/memos.
c. The files contained in /home/ben/memos are moved to the directory /home/
bob/.
d. The command fails since a directory called memos already exists in the
target directory.

Answer: a
When using the mv command to move a directory, if a directory of the same name
exists then a subdirectory is created for the files to be moved.

Which of the following tasks is not necessary when creating a new user by
editing the /etc/passwd file?
Choose one:
a. Create a link from the user's home directory to the shell the user will use.
b. Create the user's home directory
c. Use the passwd command to assign a password to the account.
d. Add the user to the specified group.

Answer: a
There is no need to link the user's home directory to the shell command. Rather,
the specified shell must be present on your system.

You issue the following command useradd -m bobm But the user cannot
logon. What is the problem?
Choose one:
a. You need to assign a password to bobm's account using the passwd
command.
b. You need to create bobm's home directory and set the appropriate
permissions.
c. You need to edit the /etc/passwd file and assign a shell for bobm's account.
d. The username must be at least five characters long.

Answer: a
The useradd command does not assign a password to newly created accounts. You

will still need to use the passwd command to assign a password.

You wish to print the file vacations with 60 lines to a page. Which of the
following commands will accomplish this? Choose one:
a. pr -l60 vacations | lpr
b. pr -f vacations | lpr
c. pr -m vacations | lpr
d. pr -l vacations | lpr

Answer: a
The default page length when using pr is 66 lines. The -l option is used to specify a
different length.

Which file defines all users on your system?
Choose one:
a. /etc/passwd
b. /etc/users
c. /etc/password
d. /etc/user.conf

Answer: a
The /etc/passwd file contains all the information on users who may log into your
system. If a user account is not contained in this file, then the user cannot log in.

Which two commands can you use to delete directories?
A) rm
B) rm -rf
C) rmdir
D) rd
E) rd -rf

Answer(s): B, C - You can use rmdir or rm -rf to delete a directory. Answer a
is incorrect, because the rm command without any specific flags will not delete
a directory, it will only delete files. Answers d and e point to a non-existent
command.

Which partitioning tool is available in all distributions?
A) Disk Druid
B) fdisk
C) Partition Magic
D) FAT32
E) System Commander

Answer(s): B - The fdisk partitioning tool is available in all Linux distributions.
Answers a, c, and e all handle partitioning, but do not come with all distributions.
Disk Druid is made by Red Hat and used in its distribution along with some
derivatives. Partition Magic and System Commander are tools made by third-party
companies. Answer d is not a tool, but a file system type. Specifically, FAT32 is
the file system type used in Windows 98.

Which partitions might you create on the mail server's hard drive(s) other
than the root, swap, and boot partitions?
[Choose all correct answers]
A) /var/spool
B) /tmp
C) /proc
D) /bin
E) /home

Answer(s): A, B, E - Separating /var/spool onto its own partition helps to ensure
that if something goes wrong with the mail server or spool, the output cannot
overrun the file system. Putting /tmp on its own partition prevents either software
or user items in the /tmp directory from overrunning the file system. Placing /
home off on its own is mostly useful for system re-installs or upgrades, allowing
you to not have to wipe the /home hierarchy along with other areas. Answers c and
d are not possible, as the /proc portion of the file system is virtual-held in RAM-
not placed on the hard drives, and the /bin hierarchy is necessary for basic system
functionality and, therefore, not one that you can place on a different partition.

When planning your backup strategy you need to consider how often you
will perform a backup, how much time the backup takes and what media you
will use. What other factor must you consider when planning your backup
strategy? _________

what to backup
Choosing which files to backup is the first step in planning your backup strategy.

What utility can you use to automate rotation of logs?
Answer: logrotate
The logrotate command can be used to automate the rotation of various logs.

In order to display the last five commands you have entered using the history
command, you would type ___________ .

Answer: history 5
The history command displays the commands you have previously entered. By
passing it an argument of 5, only the last five commands will be displayed.

What command can you use to review boot messages?
Answer: dmesg
The dmesg command displays the system messages contained in the kernel ring
buffer. By using this command immediately after booting your computer, you will
see the boot messages.

What is the minimum number of partitions you need to install Linux?
Answer: 2
Linux can be installed on two partitions, one as / which will contain all files and a
swap partition.

What is the name and path of the main system log?
Answer: /var/log/messages
By default, the main system log is /var/log/messages.

Of the following technologies, which is considered a client-side script?
A) JavaScript
B) Java
C) ASP
D) C++

Answer: A - JavaScript is the only client-side script listed. Java and C++ are
complete programming languages. Active Server Pages are parsed on the server
with the results being sent to the client in HTML

How are devices represented in UNIX?
All devices are represented by files called special files that are located in/dev
directory. Thus, device files and other files are named and accessed in the same
way. A 'regular file' is just an ordinary data file in the disk. A 'block special file'
represents a device with characteristics similar to a disk (data transfer in terms of
blocks). A 'character special file' represents a device with characteristics similar to
a keyboard (data transfer is by stream of bits in sequential order).

2. What is 'inode'?

All UNIX files have its description stored in a structure called 'inode'. The inode
contains info about the file-size, its location, time of last access, time of last
modification, permission and so on. Directories are also represented as files and
have an associated inode. In addition to descriptions about the file, the inode
contains pointers to the data blocks of the file. If the file is large, inode has indirect
pointer to a block of pointers to additional data blocks (this further aggregates for
larger files). A block is typically 8k.
Inode consists of the following fields:
• File owner identifier
• File type
• File access permissions
• File access times
• Number of links
• File size
• Location of the file data
3. Brief about the directory representation in UNIX
A Unix directory is a file containing a correspondence between filenames and
inodes. A directory is a special file that the kernel maintains. Only kernel modifies
directories, but processes can read directories. The contents of a directory are a
list of filename and inode number pairs. When new directories are created, kernel
makes two entries named '.' (refers to the directory itself) and '..' (refers to parent
directory).
System call for creating directory is mkdir (pathname, mode).

What are the Unix system calls for I/O?
• open(pathname,flag,mode) - open file
• creat(pathname,mode) - create file
• close(filedes) - close an open file
• read(filedes,buffer,bytes) - read data from an open file
• write(filedes,buffer,bytes) - write data to an open file

lseek(filedes,offset,from) - position an open file
• dup(filedes) - duplicate an existing file descriptor
• dup2(oldfd,newfd) - duplicate to a desired file descriptor
• fcntl(filedes,cmd,arg) - change properties of an open file
• ioctl(filedes,request,arg) - change the behaviour of an open file
The difference between fcntl anf ioctl is that the former is intended for any open
file, while the latter is for device-specific operations.



5. How do you change File Access Permissions?
Every file has following attributes:
owner's user ID ( 16 bit integer )
owner's group ID ( 16 bit integer )
File access mode word
'r w x -r w x- r w x'

(user permission-group permission-others permission)
r-read, w-write, x-execute
To change the access mode, we use chmod(filename,mode).
Example 1:
To change mode of myfile to 'rw-rw-r–' (ie. read, write permission for user -
read,write permission for group - only read permission for others) we give the args
as:
chmod(myfile,0664) .
Each operation is represented by discrete values
'r' is 4
'w' is 2
'x' is 1

Therefore, for 'rw' the value is 6(4+2).
Example 2:
To change mode of myfile to 'rwxr–r–' we give the args as:
chmod(myfile,0744).

6. What are links and symbolic links in UNIX file system?
A link is a second name (not a file) for a file. Links can be used to assign more
than one name to a file, but cannot be used to assign a directory more than one
name or link filenames on different computers.
Symbolic link 'is' a file that only contains the name of another file.Operation on the
symbolic link is directed to the file pointed by the it.Both the limitations of links
are eliminated in symbolic links.
Commands for linking files are:
Link ln filename1 filename2
Symbolic link ln -s filename1 filename2

7. What is a FIFO?
FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is a special
file which is said to be data transient. Once data is read from named pipe, it
cannot be read again. Also, data can be read only in the order written. It is used
in interprocess communication where a process writes to one end of the pipe
(producer) and the other reads from the other end (consumer).

8. How do you create special files like named pipes and device files?

The system call mknod creates special files in the following sequence.
1. kernel assigns new inode,
2. sets the file type to indicate that the file is a pipe, directory or special file,
3. If it is a device file, it makes the other entries like major, minor device numbers.
For example:
If the device is a disk, major device number refers to the disk controller and minor
device number is the disk.
9. Discuss the mount and unmount system calls
The privileged mount system call is used to attach a file system to a directory of
another file system; the unmount system call detaches a file system. When you
mount another file system on to your directory, you are essentially splicing one
directory tree onto a branch in another directory tree. The first argument to mount
call is the mount point, that is , a directory in the current file naming system. The

second argument is the file system to mount to that point. When you insert a cdrom
to your unix system's drive, the file system in the cdrom automatically mounts to /
dev/cdrom in your system.

10. How does the inode map to data block of a file?
Inode has 13 block addresses. The first 10 are direct block addresses of the first
10 data blocks in the file. The 11th address points to a one-level index block. The
12th address points to a two-level (double in-direction) index block. The 13th
address points to a three-level(triple in-direction)index block. This provides a very
large maximum file size with efficient access to large files, but also small files are
accessed directly in one disk read.

11. What is a shell?
A shell is an interactive user interface to an operating system services that allows
an user to enter commands as character strings or through a graphical user
interface. The shell converts them to system calls to the OS or forks off a process
to execute the command. System call results and other information from the OS are
presented to the user through an interactive interface. Commonly used shells are
sh,csh,ks etc.

12. Brief about the initial process sequence while the system boots up.
While booting, special process called the 'swapper' or 'scheduler' is created
with Process-ID 0. The swapper manages memory allocation for processes and
influences CPU allocation. The swapper inturn creates 3 children:

the process dispatcher,
• vhand and
• dbflush
with IDs 1,2 and 3 respectively.
This is done by executing the file /etc/init. Process dispatcher gives birth to the
shell. Unix keeps track of all the processes in an internal data structure called the
Process Table (listing command is ps -el).
13. What are various IDs associated with a process?



Unix identifies each process with a unique integer called ProcessID. The process
that executes the request for creation of a process is called the 'parent process'
whose PID is 'Parent Process ID'. Every process is associated with a particular
user called the 'owner' who has privileges over the process. The identification
for the user is 'UserID'. Owner is the user who executes the process. Process
also has 'Effective User ID' which determines the access privileges for accessing
resources like files.

getpid() -process id
• getppid() -parent process id
• getuid() -user id
• geteuid() -effective user id
14. Explain fork() system call.
The `fork()' used to create a new process from an existing process. The new
process is called the child process, and the existing process is called the parent. We
can tell which is which by checking the return value from `fork()'. The parent gets
the child's pid returned to him, but the child gets 0 returned to him.



15. Predict the output of the following program code
main()
{
fork();
printf("Hello World!");
}

Answer:
Hello World!Hello World!

Explanation:
The fork creates a child that is a duplicate of the parent process. The child
begins from the fork().All the statements after the call to fork() will be executed
twice.(once by the parent process and other by child). The statement before fork()
is executed only by the parent process.
16. Predict the output of the following program code

main()
{
fork(); fork(); fork();
printf("Hello World!");
}

Answer:
"Hello World" will be printed 8 times.
Explanation:
2^n times where n is the number of calls to fork()
17. List the system calls used for process management:
System calls Description

fork() To create a new process
• exec() To execute a new program in a process
• wait() To wait until a created process completes its execution
• exit() To exit from a process execution
• getpid() To get a process identifier of the current process
• getppid() To get parent process identifier
• nice() To bias the existing priority of a process
• brk() To increase/decrease the data segment size of a process.
18. How can you get/set an environment variable from a program?
Getting the value of an environment variable is done by using `getenv()'. Setting
the value of an environment variable is done by using `putenv()'.



19. How can a parent and child process communicate?
A parent and child can communicate through any of the normal inter-process
communication schemes (pipes, sockets, message queues, shared memory),
but also have some special ways to communicate that take advantage of their
relationship as a parent and child. One of the most obvious is that the parent can
get the exit status of the child.

20. What is a zombie?

When a program forks and the child finishes before the parent, the kernel still
keeps some of its information about the child in case the parent might need it - for
example, the parent may need to check the child's exit status. To be able to get this
information, the parent calls `wait()'; In the interval between the child terminating
and the parent calling `wait()', the child is said to be a `zombie' (If you do `ps', the
child will have a `Z' in its status field to indicate this.)

21. What are the process states in Unix?
As a process executes it changes state according to its circumstances. Unix
processes have the following states:
Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a signal.
Zombie : The process is dead but have not been removed from the process table.

What is Shell Scripting ?
Shell scripting, in Linux or Unix, is programming with the shell using which
you can automate your tasks. A shell is the command interpreter which is the
interface between the User and the kernel. A shell script allows you to submit a set
of commands to the kernel in a batch. In addition, the shell itself is very powerful
with many properties on its own, be it for string manipulation or some basic
programming stuff.
Ref: What is Shell Scripting?

2. The command "cat file" gives error message "--bash: cat: Command not
found". Why?
It is because the PATH variable is corrupt or not set appropriately. And hence
the error because the cat command is not available in the directories present PATH
variable.
Ref: What is PATH variable?

3. How to find the length of a string in Linux?

$ x="welcome"

$ echo ${#x}

7

Ref: Different ways to find the length of a string.

4. What are the different timestamps associated with a file?

Modification time:- Refers to the time when the file is last modified.

Access time :- The time when the file is last accessed.

Changed time :- The time when the attributes of the file are last changed.
Ref: 3 different timestamps associated with a file.

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

$ ls -lrt | grep ^-

6. How to find the last modified file or the newest file in a directory?

$ ls -lrt | grep ^- | awk 'END{print $NF}'

7. How to access the 10th command line argument in a shell script in Linux?
$1 for 1st argument, $2 for 2nd, etc... For 10th argument, ${10}, for 11th,
${11} and so on.
Ref: Positional parameters in a shell script.

8. How to find the sum of all numbers in a file in Linux?

$ awk '{x+=$0}END{print x}' file

Ref: Different ways to find the sum of all numbers in a file.

9. How to delete a file which has some hidden characters in the file name?

Since the rm command may not be able to delete it, the easiest way to delete a
file with some hidden characters in its name is to delete it with the find command
using the inode number of the file.

$ ls -li

total 32

9962571 -rw-r--r-- 1 guru users 0 Apr 23 11:35

$ find . -inum 9962571 -exec rm '{}' \;

10. Using the grep command, how can you display or print the entire file
contents?

$ grep '.*' file

Ref: 15 different ways to display or print the file contents

11. What is the difference between a local variable and environment variable
in Linux?
A local variable is the one in which the scope of the variable is only in the
shell in which it is defined. An environment variable has scope in all the shells
invoked by the shell in which it is defined.
Ref: Difference between set, setenv and export.

12. What does the 'execute' permission in a directory stand for?
Without the execute permission on a directory, the user will not be able to
traverse or in other words, do a "cd" to the directory.
Ref: File Permissions vs Directory Permissions

13. How to find the total number of arguments in a shell script in Linux?
The shell special variable, $# ,contains the total number of arguments passed to
a shell script.
Ref: Positional parameters in a shell script.

14. How to remove the Control-M character from a file in Linux?

$ dos2unix file

Ref: Different ways to remove the Control-M characters from a file.

15. In which file should a variable be set in order to make the setting
permanent?
The variable should be set in the profile file to make the setting permanent. The
appropriate profile depends on the default shell being set for the user.
Ref: Profile file for different shells.

16. What is a she-bang line in a shell script?
She-bang line in a shell script is the first line, if present. It starts with '#!'
and followed up with a full path of a shell. The shell specified indicates the shell in
which this script will be run. The entry of she-bang is not mandatory, however, if
present, should be the first line of the script. With a number of shells available and
syntax being specific for a given shell, it is always good to specify the she-bang
line in a shell script.

17. A file contains many lines, and each line containing multiple words. How
to find out the unique words and the word count of each of the words?

$ cat file

apple orange

banana apple orange

papaya

$ awk '{for(i=1;i<=NF;i++)a[$i]++;}END{for(i in a){print i, a[i];}}' file

banana 1

apple 2

orange 2

papaya 1

18. What is an internal command in Linux?
Internal commands are also called shell built-in commands. Example:
cd,fg. Since these are shell built-in, no process is created while executing these
commands, and hence are considered to be much faster.
Ref: Internal vs External command.

19. x and y are two variables containing numbers? How to add these 2
numbers?

$ expr $x + $y

Ref: Different ways to do arithmetic operations in Linux

20. How to add a header record to a file in Linux?

$ sed -i '1i HEADER' file

Ref: Different ways to add header and trailer record to a file.

21. How to find the list of files modified in the last 30 mins in Linux?

$ find . -mmin -30

22. How to find the list of files modified in the last 20 days?

$ find . -mtime -20

23. How to find the files modified exactly before 30minutes?

$ find . -mmin 30

Ref: find files modified before X days, X hours and X mins in Linux.

24. A string contains a absolute path of a file. How to extract the filename
alone from the absolute path in Linux?

$ x="/home/guru/temp/f1.txt"

$ echo $x | sed 's^.*/^^'

Ref: Different ways to print the filename from the absolute path.

25. How to find all the files created after a pre-defined date time, say after
10th April 10AM?
This can be achieved in 2 steps:
1. Create a dummy file with the time stamp, 10th April 10AM.
2. Find all the files created after this dummy file.

$ touch -t 1004101000 file

$ find . -newer file

26. How to print the contents of a file line by line in Linux?

$ while read line

> do

> echo $line

> done < file

27. The word "Unix" is present in many .txt files which is present across
many files and also files present in sub directories. How to get the total count
of the word "Unix" from all the .txt files?

$ find . -name *.txt -exec grep -c Unix '{}' \; | awk '{x+=$0;}END{print x}'

28. How to get tomorrow's date in Linux?

$ date -d "1 day"

Ref: GNU date in Linux

29. How to join all lines in a file using comma?

$ paste -s -d, file

30. How to join all lines in a file without any delimiter?

$ paste -s --delimiter="" file

Ref: Join all lines in a file in Linux

31. How to join every 2 lines in a file in Linux?

$ sed 'N;s/\n//' file

Ref: Join every 2 lines in a file in Linux.

32. A shell script will ask for 3 inputs. The user will not be physically present
to be able to give it manually. How can the script be run without having to
manually give the input?
Put those 3 input values in a file, and make the script to read this file as input.
For example:
Assume the 3 values to be : 3, 10 and 20:

$ cat file

3

10

20

and assuming the script is hello.sh, run it like:

./hello.sh < file

33. How to find the total number of a lines in a file in Linux?

$ wc -l file | awk '{print $1}'

Ref: Different ways to find the total lines in a file in Linux.

34. How to print the first line or the header record in a file?

$ head -1 file

Ref: Different ways to print the first line of a file in Linux.

35. How to replace all occurrences of "Unix" to "Linux" in a file?

$ sed 's/Unix/Linux/g' file

36. How to make the above changes permanent in the file?

$ sed -i 's/Unix/Linux/g' file

37. How to replace only the first occurrence of "Unix" to "Linux" in a string
in Linux?

$ sed 's/Unix/Linux/' file

38. How to replace only the second occurrence of "Unix" to "Linux" in a
string in Linux?

$ sed 's/Unix/Linux/2' file

In fact, to replace nth occurrence of a string in a file, it is:

$ sed 's/Unix/Linux/n' file #where n is the nth occurrence

Ref: Replace or substitute file contents - Part 1

39. How to add leading zeros to every line in a file in Linux?

$ sed 's/^/0000/' file

40. How to add trailing zeros to every line in a file in Linux?

$ sed 's/$/00/' file

Ref: sed replace or substitute file contents - Part 2

41. How to get yesterday's date in Linux?

$ date -d "1 day ago"

42. I have a file with SQL commands. How can I open a sqlplus session in
Linux and run this SQL file?

$ sqlplus guru/unix11@XE @file.txt

where file.txt is the ASCII file containing the sql instructions.
Ref: Different ways to connect to sqlplus from Linux.

43. The ps command will disclose the sqlplus connect string if any sqlplus
session is ON. How to prevent the sqlplus connect string from appearing in
the ps command in Linux?
While connecting to sqlplus, instead of connecting in the normal way, connect
as below:

$ sqlplus /nolog

> connect guru/unix11@XE

Ref: Secure sqlplus connection in Linux.

44. How to rename a group of files from .txt to .exe in Linux?

for i in *.txt

do

x=`basename $i .txt`

mv $i $x.exe

done

Ref: 3 different ways to rename a group of files in Linux.

45. After logging in to your account in Linux, you did "cd log". There was
no "log" directory under the current directory, still the "cd" command
traversed to a log directory under a different location? How it happened?
It is because the CDPATH variable is set.
Ref: What is CDPATH?

46. How to zero pad a number in Linux?
Say, to zero pad a number to 4 places:

$ x=20

$ printf "%04d\n" $x

Ref: Different ways to zero pad a number in Linux.

46. How to find all the .c and .h files in Linux?

$ find . -name "*.[ch]"

47. How to find the list of all the .c files and display only the file name, instead
of the default find output which includes the relative path?

$ find . -name *.c | sed 's^.*/^^'

Ref: find files by name or extension or part of file name.

48. How to copy a file with the same time stamp as the source file in Linux?

$ cp --preserve=timestamp file1 file2

49. How to copy a file "file1" to "file2" by passing only one argument to cp
command?

$ cp file{1,2}

Ref: cp - 10 different cp command examples in Linux.

50. What is the difference between the source command and dot(.) command
in Linux?
No difference. Both are used for sourcing a file in Linux. bash, csh and some
more shells using source command, whereas ksh uses dot(.) command to source a
file.

Explain this entry /shared 192.168.1.0/255.255.255.0(sync,rw)
allows all systems with 192.168.1.* IP addresses read-write access to the /shared/
directory:
Q: - What will happened if a space is given inbetween allowed_hosts and
(options)

If a space is included, the options are applied to any and all IP addresses, which
can be quite dangerous if write permission is granted.
Q: - What is the role of "sync" option for NFS server

If sync is specified, the server waits until the request is written to disk before
responding to the client. The sync option is recommended because it follows the
NFS protocol.

Q: - How to retrieve a list of clients connected to the NFS server ?

To retrieve a list of clients connected to the NFS server, use the showmount
command
from a shell prompt. To also show the directories the clients are connected to, use
the
showmount -a command.
Q: - Name of Configuration file for NFS Server ?

/etc/exports
Q: - What is meaning of "no_root_squash" option ?

Treat remote root user as local root. Do not map requests from root to the anony-
mous user and group ID.
Q: - What is NFS ?

NFS stands for Network File System. NFS was originally developed by Sun
Microsystems in the 1980's. NFS allows remote hosts to mount file systems over
a network and interact with those file systems as though they are mounted locally.
This enables system administrators to consolidate resources onto centralized
servers on the network.
Q: - Which NFS versions are available ?

NFS Version 2
NFS Version 3
NFS Version 4
Q: - What is different between NFS Version 2 & 3 ?

nfs 2 default 8kb transfer rate,it did not check the authentication at the time
connection.client wants to access unauthorized file it shows error messages
like "write error","read error" nfs 3 32kb transfer rate. It check at the time
connection- ACL Support
Q: - Can we grant access by Username and password for nfs share?
No, access is granted only for IP address.

Q: - What is the role of "all_squash" option?
Treat all client users as anonymous users. Map all user and group IDs to the
anonymous user and group ID.

Q: - What is the role of "root_squash" option?

All requests from the user root are translated or mapped as if they came from the
user anonymous (default).
Q: - Explain option "all_squash"?
The UID and GID of exported files are mapped to the user anonymous. It is good
for public directories.
Q: - Explain "exportfs" command?
The exportfs command is used to maintain the current table of exported file
systems for NFS.
Q: - Explain command "/usr/sbin/exportfs -f"?
It will flush everything out of the kernels export table. Any clients that are active
will get new entries added by mountd when they make their next request.
Q: - Which option is used with exportfs command to display the current
export list, also displays the list of export options?
exportfs -v
Q: - Which option is used with exportfs command to re-export all directories?
exportfs -r
Q: - How you will export directory (/data) to host 192.168.1.51, allowing
asynchronous writes without adding the entry in /etc/exports file?
# exportfs -o async 192.168.1.51:/data
Q: - Is rpc.mountd daemon supports TCP_WRAPPERS?
Yes, The rpc.mountd daemon is protected by the tcp_wrappers. You have to give
the clients access to rpc.mountd if they should be allowed to use NFS Server.
Q: - Explain "nfsstat" command?
The nfsstat command displays the statistics about NFS client and NFS server
activity.
Q: - What do you understand by "nfsstat -o all -234" command?
It will Show all information about all versions of NFS.
Q: - What do you understand by "nfsstat --nfs --server -3" command?
It will show statistics for NFS version 3 server.
Q: - Can NFS share mounted on Window XP and Justify your answer?
No, Window XP operating system doesn’t support nfs protocol.
Q: - 192.168.1.51:/data is exported by NFS Server and i want to add this NFS
share to client /etc/fstab file. How you will add this entry in /etc/fstab file?
# device
mount-point fs-type options
dump fsckorder
192.168.1.51:/data
/mnt
nfs
rw
0
0
Q: - Explain "Soft Mounting" option at NFS Client?

if a file request fails, the NFS client will report an error to the process on the client
machine requesting the file access. if it cannot be satisfied (for example, the server
is down), then it quits. This is called soft mounting.

Q: - Explain "Hard Mounting" option at NFS Client?
If a file request fails, the NFS client will report an error to the process on the client
machine requesting the file access. if it cannot be satisfied, then it will not quit
until the request is satisfied. This is called Hard mounting.
Q: - What is "portmap"?
The portmapper keeps a list of what services are running on what ports. This list
is used by a connecting machine to see what ports it wants to talk to access certain
services.
Q: - How you will check "portmap" service is running or not?
rpcinfo -p
Q: - I am unable to mount a NFS share. How will you trace out the reason?
Firstly, check that you have permissions to mount nfs share or not. Check /etc/
exports file.
Secondly you can get RPC error: Program Not Registered (or another "RPC" error)
For this check your NFS server and portmap service running or not by "rpcinfo -p"
Q: - Can I modify export permissions without needing to remount clients in
order to have them take effect?
Yes. The safest thing to do is edit /etc/exports and run "exportfs -r".

Write command to list all the links from a directory?
In this UNIX command interview questions interviewer is generally checking
whether user knows basic use of "ls" "grep" and regular expression etc
You can write command like:
ls -lrt | grep "^l"

2. Create a read-only file in your home directory?
This is a simple UNIX command interview questions where you need to create a
file and change its parameter to read-only by using chmod command you can also
change your umask to create read only file.
touch file
chmod 400 file

How will you find which operating system your system is running on in
UNIX?
By using command "uname -a" in UNIX

4. How will you run a process in background? How will you bring that into
foreground and how will you kill that process?
For running a process in background use "&" in command line. For bringing
it back in foreground use command "fg jobid" and for getting job id you use
command "jobs", for killing that process find PID and use kill -9 PID command.
This is indeed a good Unix Command interview questions because many of
programmer not familiar with background process in UNIX.

5. How do you know if a remote host is alive or not?
You can check these by using either ping or telnet command in UNIX. This
question is most asked in various Unix command Interview because its most basic
networking test anybody wants to do it.

6. How do you see command line history in UNIX?
Very useful indeed, use history command along with grep command in unix to
find any relevant command you have already executed. Purpose of this Unix
Command Interview Questions is probably to check how familiar candidate is from
available tools in UNIX operation system.

7. How do you copy file from one host to other?
Many options but you can say by using "scp" command. You can also
use rsync command to answer this UNIX interview question or even sftp would be
ok.

8. How do you find which process is taking how much CPU?
By using "top" command in UNIX, there could be multiple follow-up UNIX
command interview questions based upon response of this because “TOP”
command has various interactive options to sort result based upon various
parameter.

9. How do you check how much space left in current drive ?
By using "df" command in UNIX. For example "df -h ." will list how full your
current drive is. This is part of anyone day to day activity so I think this Unix
Interview question will be to check anyone who claims to working in UNIX but
not really working on it.

10. What is the difference between Swapping and Paging?
Swapping:
Whole process is moved from the swap device to the main memory for execution.
Process size must be less than or equal to the available main memory. It is easier to
implementation and overhead to the system. Swapping systems does not handle the
memory more flexibly as compared to the paging systems.
Paging:
Only the required memory pages are moved to main memory from the swap
device for execution. Process size does not matter. Gives the concept of the virtual
memory. It provides greater flexibility in mapping the virtual address space into
the physical memory of the machine. Allows more number of processes to fit in the
main memory simultaneously. Allows the greater process size than the available
physical memory. Demand paging systems handle the memory more flexibly.

What is difference between ps -ef and ps -auxwww?

This is indeed a good Unix Interview Command Question and I have faced
this issue while ago where one culprit process was not visible by execute ps –
ef command and we are wondering which process is holding the file.

ps -ef will omit process with very long command line while ps -auxwww will list
those process as well.

How do you find how many cpu are in your system and there details?
By looking into file /etc/cpuinfo for example you can use below command:
cat /proc/cpuinfo

3. What is difference between HardLink and SoftLink in UNIX?
I have discussed this Unix Command Interview questions in my blog
post difference between Soft link and Hard link in Unix

4. What is Zombie process in UNIX? How do you find Zombie process in
UNIX?
When a program forks and the child finishes before the parent, the kernel still
keeps some of its information about the child in case the parent might need it - for
example, the parent may need to check the child's exit status. To be able to get this
information, the parent calls 'wait()'; In the interval between the child terminating
and the parent calling 'wait()', the child is said to be a 'zombie' (If you do 'ps', the
child will have a 'Z' in its status field to indicate this.)
Zombie : The process is dead but have not been removed from the process
table.

5. What is "chmod" command? What do you understand by this line “r-- -w- -
-x?

6. There is a file some where in your system which contains
word "UnixCommandInterviewQuestions” How will find that file in Unix?
By using find command in UNIX for details see here 10 example of using find
command in Unix

7. In a file word UNIX is appearing many times? How will you count number?
grep -c "Unix" filename

8. How do you set environment variable which will be accessible form sub
shell?
By using export for example export count=1 will be available on all sub shell.

9. How do you check if a particular process is listening on a particular port on
remote host?
By using telnet command for example “telnet hostname port”, if it able to
successfully connect then some process is listening on that port. To read more
about telnet read networking command in UNIX

10. How do you find whether your system is 32 bit or 64 bit ?
Either by using "uname -a" command or by using "arch" command.

Advanced UNIX Interview Questions and Answers

1. How do you find which processes are using a particular file?
By using lsof command in UNIX. It wills list down PID of all the process which is
using a particular file.

2. How do you find which remote hosts are connecting to your host on a
particular port say 10123?
By using netstat command execute netstat -a | grep "port" and it will list the entire
host which is connected to this host on port 10123.

3. What is nohup in UNIX?

4. What is ephemeral port in UNIX?
Ephemeral ports are port used by Operating system for client sockets. There is a
specific range on which OS can open any port specified by ephemeral port range.

5. If one process is inserting data into your MySQL database? How will you
check how many rows inserted into every second?
Purpose of this Unix Command Interview is asking about "watch" command in
UNIX which is repeatedly execute command provided with specified delay.

6. There is a file Unix_Test.txt which contains words Unix, how will you
replace all Unix to UNIX?
You can answer this Unix Command Interview question by using SED command
in UNIX for example you can execute sed s/Unix/UNIX/g fileName.

7. You have a tab separated file which contains Name, Address and Phone
Number, list down all Phone Number without there name and Addresses?
To answer this Unix Command Interview question you can either you AWK or
CUT command here. CUT use tab as default separator so you can use
cut -f3 filename.

8. 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.

9. How do you find for how many days your Server is up?
By using uptime command in UNIX

10. You have an IP address in your network how will you find hostname and
vice versa?
This is a standard UNIX command interview question asked by everybody and I
guess everybody knows its answer as well. By using nslookup command in UNIX



















No comments:

Post a Comment