Unix Shell Scripting Interview Questions

  • (4.0)

Unix Shell Scripting Interview Questions

If you're looking for Unix Shell Scripting Interview Questions for Experienced or Freshers, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research Unix Shell Scripting has a market share of about 17%. So, You still have opportunity to move ahead in your career in Unix Shell Scripting. Mindmajix offers Advanced Unix Shell Scripting Interview Questions 2018 that helps you in cracking your interview & acquire dream career as Unix Shell Scripting Developer.

Are you intereted in taking up for Unix Shell Scripting Certification Training? Enroll Now Unix Shell Scripting Training!


C Shell – Beginner

Q. What must you do before you are able to run your new script for the first time by its name or with an alias?
You must make it executable, that is to execute the command:
chmod +x scriptname

Q. The following command is included in the .login script of a user:
alias whois ´grep !ˆ /etc/passwd´
What will be the output, when the user issues the following?
who is guru
If there is a defined user account named “guru”, or the string guru is contained elsewhere in /etc/passwd file, then the output will be the entry which contains the string “guru”, otherwise, it will be an empty line.

Q. If the condition If ( -r  filename ) fails (returns false), what are the possible reasons?
The possible reasons are:
a) filename is not readable by the owner of the process
b) filename does not exist

Q. Which is the difference between the next two statements?
set var  = 99
@ var = 99
Using the typical assignment form (set …), the value assigned in var is the string 99. Using the @, the value is the integer 99.

Q. Given the code snippet:
@ n = 5
while ($n)
# actions

What actions should be performed inside the loop, in order to get out of this loop?
Any command that changes the value of variable n, for it to become 0 sometime. E.g., @ n—

Q. What will the output of the following commands be? Explain.
set names  = (Kathrin Chris Jacob)
shift names
echo $#names
The output will be 2.
shift command gets rid of the first element of the array names. So, the echo command will display 2 as the number of elements of the array.

Q. What does the command rehash do?
rehash recomputes the internal hash table for the PATH variable. If the new command resides in a directory not listed in PATH, add this directory to PATH, and then use rehash.

Q. How could you ensure that a script will be run in csh?
The first line of the script could be used to define the shell you want to use, as follows:
This is sufficient to run the script in csh.

Q. Given that script1 is an executable C shell script situated in directory /home/myhomedir/project1/data/dir1, use three ways to run it, explaining the pros and cons.
a) cd/home/myhomedir/project1/data/dir1/script1 (You should first cd to the directory path)
b) /home/myhomedir/project1/data/dir1/script1 (You should include the absolute directory path)
c) script1 (shortest form, but it works only if the directory path is added to the PATH environment variable of the user)

Q. What will be the value of the sixrem variable, after executing this command?
@ sixrem = $data[2] % 6
The expression divides the value of second element of the data array by 6 and assigns the remainder of the division to the sixrem variable.

Q. Name two ways to obtain the length of a string, giving a simple example for each one.
The two ways to obtain the length of a string are:
a) Using the wc command:
set string = “any string”
@ ln = `echo $string | wc -c` -1
b) Using the awk function length:
set string = “any string”
set ln = `echo $string | awk ‘{print length($0)}’`

Q. Create a script that displays a list of regular files from the current directory.
#!/bin/csh -f
foreach i (*)
if ( -f  $i ) then
print $i

Q. Describe in short the word completion feature of the tcsh shell.
Completion works anywhere in the command line, not at just the end, for both commands and filenames. Type part of a word and hit the Tab key, and the shell replaces the incomplete word with the complete one in the input buffer. The completion also adds a “/” to the end of completed directories and a space to the end of other words. The shell parses the buffer to determine whether the word you try to complete should be completed as a command, filename or variable. The first word in the buffer and the first word following ‘;’, ‘|’, ‘|&’, ‘&&’ or ‘||’ is considered to be a command. A word beginning with ‘$’ is considered to be a variable. Anything else is a filename. An empty line is ‘completed’ as a filename.

Q. In tcsh, how are the remaining choices (if any) listed whenever the word completion fails?
The remaining choices (if any), are listed only if the shell variable autolist is set.

Q. In tcsh, how do you disable filename substitution?
noglob shell variable can be set to disable the filename substitution feature.

Q. Compare the sched tcsh built-in command with the UNIX/Linux at command.
These commands are similar but not the same. sched command runs directly from the shell, so it has access to shell variables and settings at command can run a scheduled command at exactly the specified time.

Q. Schedule a prompt change at 10:55 as a reminder for an oncoming event.
sched 10:55 set prompt = ‘It’s time for the important meeting: >’

Q. What is the impact of -f option in the first line of a csh script?
#!/bin/csh -f)
Using option -f, the shell does not load any resource or startup files (.cshrc for a script), or perform any command hashing, and thus starts faster.

Q. How can you start a job in the background, and then terminate your login session, without terminating the background job?
We can start a job in the background and then terminate our login session, without terminating the background job using “no hangup” command, nohup:
nohup command > output_file &

Q. Which is the difference between
echo c{1,4,2,5,1}
echo [c]{1,4,2,5,1}?

The first echo will display c1 c4 c2 c5 c1, while the second displays only c1.

Q. Display the first and last arguments of a script, regardless of the number of arguments, and without a loop.
my_var3 = $#argv
echomy_var1: $argv[$1]
echomy_last_var: $argv[$my_var3]

Q. How will you set the ‘search path’ in csv?
Search path in csv can be set as follows:
a) setenv PATH “/myfolder1 /bin: /myfolder2 /myfile3”
b) using list
set path = ( /myfolder1 /bin /myfolder2 /myfile3 )

Q. Create a tar archive into /home/user1/myarch.tar, including all files ending in .c, .h, .l, .y,.o and .cc and also the Makefile from two directories, ~/dir1 and ~/dir2.
tar cvf /home/user1/myarch.tar ~/{dir1,dir2}/{Makefile,*.{c,h,l,o,y,cc}}
tar cvf /home/user1/myarch.tar ~/dir1/Makefile ~/dir1/*.[chloy] ~/dir1/*.cc ~/dir2/Makefile ~/dir2/*.[chloy] ~/dir2/*.cc

Q. Your script must be executed with exactly two arguments, otherwise would be terminated. Write a code to implement these checks.
if ($#argv <> 2) then
echo “Usage: $0 arg1 arg2”
echo “You must give exactly two parameters”
exit 20

Q. Write a pipeline that reads from the j-th line up to the k-th line of a text file, without using awk.
set total = `cat textfile | wc -l`
set j = 10
set k = 18
@ count = $k – $j
head -$k textfile | tail -$count

C Shell – Intermediate

Q. Explain the following commands:
set names  = (John Kathrin Chris Jacob)
set names = ($names[1-2] Angela $names[3-])
First command creates an array named names with the four names as its elements.
Second command adds name Angela between Kathrin and Chris.

Q. How could you move cursor to specified coordinates on screen? (tcsh)
We can move the cursor to specified coordinates on the screen using echotc cm column row

Q. What is the result of this loop?
foreach i ([A-Z]*) ? mv $i $i.csh ? end
The loop renames all files that begin with a capital letter, adding the “extension” .csh.

Q. Assuming there is a label cleanup somewhere in a script, explain the command onintr cleanup
The script will branch to label cleanup if it catches an interrupt signal.

Q. Is there a way to repeat a command for a predefined number of times, without using a counter-controlled loop?
We can repeat a command for a predefined number of times, without using a counter-controlled loop using the repeat command, e.g.,
repeat 5 ls >> listings

Q. csh and tcsh both support the filename & command completion feature. But the feature works differently in csh than in tcsh. Name the differences.
tcsh automatically completes filenames and commands when the Tab key is hit.
csh does so only when the filec variable is set, after the Esc key is hit.

Q. Name the special login files for csh&tcsh in the order used by each shell.
If the command is executed from the (“/etc/csh.cshrc& /etc/csh.login”) system files, the login shell will be started.
a) It will run the commands given in the files present in the home directory of the user.~/.cshrc or ~/.tcshrc:During shell startup, it gets executed for each instance of the shell. If  ~/.cshrcs present, ‘tcsh’ uses this file else executes ‘~/.tcshrc’
b) ~/.login: at login it is executed after .cshrcby login shell
c) ~/.cshdirs: After .login (tcsh), it is executed by login shell

Q. What do the following lines do? Explain the differences.
ls > filename
ls  >! Filename

In both forms, the output of ls command is redirected to filename. If filename does not exist, it will be created, otherwise it will be truncated. When the first form is used, if shell parameter noclobber is set and filename is an existing file, an error results. The ‘!’ in the second form is used to suppress that check.

Q. You can run a script by its name, using an alias or using source. Explain the differences in using each of the three methods. When is it suitable to use each method?
A script executed by name is not run in current process (a child process is created to run the script), so this method is suitable to be used only if the environment variables and globally defined aliases (in $HOME/.cshrc) should be known to the script.
The method that executes a script using an alias is a variant of executing the script by name. In addition, if the alias is defined from shell prompt, it applies only to the current process. To make the alias global, you must define it in $HOME/.cshrc, but be careful to keep the number of aliases included there to a relatively small number.
With the third method, the script runs in the current process, thus, any aliases defined in the current process will be known to your script.

Q. How could you override a defined alias? Give a simple example.
To override an alias, precede the alias with backslash. Fox example, if you have an alias named rm which runs a custom script, if you want to run the command rm instead of the rm alias, you can do it as shown below:
rm filename

Q. You plan to write a script that will process the file passed to it as the only argument on the command line. So, your script must accept at least one argument and this single or first argument must be an existing file. Write the necessary checks, displaying the appropriate messages.
if ( $#argv == 0 ) then
echo Error: A file name must be supplied as argument
exit 10
else if ( ! -e $1 ) then
echo Error:  $1 is not an existing file
exit  11
commands to process the file

Q. Write a code excerpt that processes (here, just displays) the elements of an array, from the first one to the last one.
set myarray = (value1, value2, value3, value4, value5)
set i = 1
while ( $#myarray > 0 )
echo “$i array’s element is: $myarray[1]”
shift myarray
@ i++
set myarray = (value1, value2, value3, value4, value5)
set i = 1
foreach val ( $myarray[*] )
echo “$i array’s element is: $val”
@ i++

Q. Complete the last echo command with a descriptive message in the following script. In other words, explain the value of pct variable.
set duout = (`du -sk ~`)
@ dir_size = $duout[1]
set dfout = (`df -k | grep /home`)
@ home_size = $dfout[2]
@ pct = $dir_size * 100 / $home_size
echo “… $pct …”

echo “Your home directory takes $pct % of /home filesystem”

Q. Extract just the mode of a given file, using two different ways.
The mode of a given file can be extracted in the following ways:
a) set file_mode = `ls -l filename | tail -1 | cut -f1 -d” ” | cut -c2-`
b) set file_mode = `ls -l filename | awk ‘ /^-/ {print substr($1,2)}’`

Q. Which is the output of the following excerpt?
netstat -an | awk ‘/SHED/ {split($4,c,”.”); print “Connection to ” c[4] ” from ” $5}’ | sort -nt” ” -k 3
Lines in the format “Connection to port_number from IP_Address”, for each established connection, sorted by port_number.

Q. Find the position of a substring in a given string. Display a message if the string does not contain this substring.
set string = “any string”
set sub = “str”
set pos = ` echo $string | awk -v s=$sub ‘{print index($0,s)}’`
if ( $pos == 0 ) then
echo “$string does not contain the substring $sub”
echo “$sub first occurrence in $string starts in position $pos”

Q. Change the case of a string.
set string = “C Shell Programming”
set ustring = `echo $string | awk ‘{print toupper($0)}’` # = “C SHELL PROGRAMMING”
set lstring = `echo $string | awk ‘{print tolower($0)}’` # = “c shell programming”

Q. Assume that in a script the value of a variable limt becomes equal to 92.1. Display the message:
Upper limit 92.10% in your_system
set system = `hostname`
printf “Upper limit %f.2%% in the %s” $limt $system

Q. Suppose a script contains the following snippet:
set fl = /home/dbuser5/reports/fs_report1.txt
echo $fl:e
echo $fl:r
echo $fl:t
echo $fl:h
What do you expect to be displayed?


Q. Create a script that converts the filenames from current directory to lower case letters.
#!/bin/csh -f
foreachmy_old_file1 (`ls`)
setmy_new_ file1 = `echo $my_old_file1 | tr ´[A-Z]´ ´[a-z]´`
if (“$my_new_ file1” == “$my_old_file1”) then
mv $ my_old_file1 $my_new_ file1

Q. Name some basic differences between csh and tcsh.
tcsh includes a command-line editor, file name and command completion features, and enhanced job control, in comparison with the Berkeley csh.

Q. Compare the tcsh shell variables correct and autocorrect.
autocorrect can be set to correct the word to be completed before any completion attempt. correct can be set to ‘cmd’ to correct command names or to ‘all’ to correct the entire line, each time return is hit.

Q. What is the purpose of the special alias shell?
The shell special alias can be set to specify an interpreter other than the shell itself.

Q. Which is the method to bind the keys to the standard vi or emacs bindings?
Shell’s built-in command is bindkey. Its -e option binds all keys to standard emacs bindings, while -v option binds to standard vi bindings.

Q. Which is the purpose of shell’s variable color?
Shell’s variable color, if set, enables color display for the built in ls-F and it passes –color=auto to ls.

Q. Set your prompt to display username@hostname: pwd>
It can be done as follows:
set prompt = “%n@%m: %/ >”

Q. How can you start (from shell prompt) 2 commands “in the background”, ensuring that the second command will start after the completion of the first one?
It can be done as follows:
(command 1 ; command 2)  &

Q. What is a shell?
Shell is a interface between user and the kernel. Even though there can be  only one kernel ; a system can have many shell running simultaneously . Whenever  a user enters a command  through keyboard the shell communicates with the kernel  to execute it and then display the output to the user.

Q. What are the different types of commonly used shells  on a typical linux system?
csh,ksh,bash,Bourne . The most commonly used and advanced shell used today is “Bash” .

Q. What is the equivalent of a file shortcut that we have on window on a Linux system?
Shortcuts are created using “links” on Linux. There are two types of links that can be used namely “soft link” and “hard link”

Q. What is the difference between soft and hard links?
Soft links are link to the file name and can reside on different filesytem as well; however hard links are link to the inode of the file and has to be on the same filesytem as that of the file. Deleting the orginal file makes the soft link inactive (broken link) but does not affect the hard link (Hard link will still access a copy of the file)

Q. How will you pass and access arguments to a script in Linux?
Arguments can be passed as:
scriptName “Arg1” “Arg2”….”Argn” and can be accessed inside the script as $1 , $2 .. $n

Q. What is the significance of $#?
$# shows the count of the arguments passed to the script.

Q. What is the difference between $* and $@?
$@ treats each quoted arguments as separate arguments but $* will consider the entire set of positional parameters as a single string.

Q. Use sed command to replace the content of the file (emulate tac command)
1. if cat file1
Then O/p should be

1. sed ‘1! G; h;$!d’ file1

Here G command appends to the pattern space,
h command copies pattern buffer to hold buffer
and d command deletes the current pattern  space.

Q. Given a file,  replace all occurrence of word “ABC” with “DEF” from 5th line till end in only those lines that contains word “MNO”
1    sed –n ‘5,$p’ file1|sed ‘/MNO/s/ABC/DEF/’

Q. Given a file , write a command sequence to find the count of each word.
1. tr –s  “(backslash)040” where “(backslash)040” is octal equivalent of “space”
2. ”(backslash)011” is octal equivalent of “tab character” and
3. “(backslash)012” is octal equivalent of newline character.

Q. How will you find the 99th line of a file using only tail and head command?
tail +99 file1|head -1

Check Out Unix Shell Scripting Tutorials

Q. Print the 10th line without using tail and head command.
1    sed –n ‘10p’ file1

Q. In my bash shell I want my prompt to be of format  ‘$”Present working directory”:”hostname”>  and load a file containing a list of user defined functions as soon as I login , how will you automate this?
In bash shell we can create “.profile”  file which automatically gets invoked as soon as I login and write the following syntax into it.
1    export PS1=’$ `pwd`:`hostname`>’ .File1
Here File1 is the file containing the user defined functions and “.” invokes this file in current shell.

Q. Explain about “s” permission bit in a file?
“s” bit is called “set user id” (SUID) bit.
“s” bit on a file causes the process to have the privileges of the owner of the file during the instance of the program.
Eg: Executing “passwd” command to change current password causes the user to writes its new password to shadow file even though it has “root” as its owner.

Q. I want to create a directory such that anyone in the group can create a file and access any person’s file in it but none should be able to delete a file other than the one created by himself.
We can create the directory giving read and execute access to everyone in the group and setting its sticky bit “t” on as follows:

5mkdir direc1
chmod g+wx direc1
chmod +t direc1

Q. How can you find out how long the system has been running?
Command “uptime”

Q. How can any user find out all information about a specific user like his default shell, real life name, default directory,when and how long he has been using the sytem?
finger  “loginName”                  …where loginName is the  login name of  the
user whose  information is expected.

Q. What is the difference between $$ and $!?
$$ gives the process id of the currently executing process whereas $! shows the process id of the process that recently went into background.

Q. What are zombie processes?
These are the processes which have died but whose exit status is still not picked by the parent process. These processes even if not functional still have its process id entry in the process table.

Q. How will you copy file from one machine to other?
We can use utilities like “ftp” ,”scp” or “rsync” to copy file from one machine to other.
Eg: Using ftp:
ftp hostname
>put file1
Above copies file file1 from local system to destination system whose hostname is specified.

Q. I want to monitor a continuously updating log file, what command can be used to most efficiently achieve this?
We can use tail –f filename. This will cause only the default last 10 lines to be displayed on std o/p which continuously shows  the updating part of the file.

Q. I want to connect to a remote server and execute some commands, how can I achieve this?
We can use telnet to do this:
telnet hostname –l user
>Enter password
>Write the command to execute

Q. I have 2 files and I want to print the records which are common to both.
We can use “comm” command as follows:
comm -12 file1 file2               … 12 will suppress the content which are
unique to 1st and 2nd  file respectively.

Q. Write a script to print the first 10 elemenst of Fibonacci series.
echo $a
echo $b
for I in 1 2 3 4 5 6 7 8
echo $b

Q. How will you connect to a database server from linux?
We can use isql utility that comes with open client driver  as follows:
isql –S serverName –U username –P password

Q. What are the 3 standard streams in Linux?
0 – Standard Input
1 – Standard Output
2 – Standard Error

Q. I want to read all input to the command from file1 direct all output to file2 and error to file 3, how can I achieve this?
command file2 2>file3

Q. What will happen to my current process when I execute a command using exec?
“exec” overlays the newly forked process on the current  process ; so when I execute the command using exec, the command gets executed on the current shell without creating any new processes.
Eg: Executing “exec  ls”  on command prompt will execute ls and once ls exits, the process will shut down

Q. How will you emulate wc –l using awk?
awk ‘END {print NR} fileName’

Q. Given a file find the count of lines containing word “ABC”.
grep –c  “ABC” file1

Q. What is the difference between grep and egrep?
egrep is Extended grep that supports added grep features like “+” (1 or more occurrence of previous character),”?”(0 or 1 occurrence of previous character) and “|” (alternate matching)

Q. How will you print the login names of all users on a system?
/etc/shadow file has all the users listed.
awk –F ‘:’ ‘{print $1} /etc/shadow’|uniq -u

Q. How to set an array in Linux?
Syntax in ksh:
Set –A arrayname= (element1 element2 ….. element)
In bash
A=(element1 element2 element3 …. elementn)

Q. Write down the syntax of “for “ loop
for  iterator in (elements)
execute commands

Q. How will you find the total disk space used by a specific user?
du  -s /home/user1             ….where user1 is the user for whom the total disk
space needs to be found.

Q. Write the syntax for “if” conditionals in linux?
If  condition is successful
execute commands
execute commands

Q. What is the significance of $? ?
$? gives the exit status of the last command that was executed.

Q. How do we delete all blank lines in a file?
1    sed  ‘^ [(backslash)011(backslash)040]*$/d’ file1
where (backslash)011 is octal equivalent of space and
(backslash)040 is octal equivalent of tab

Q. How will I insert a line “ABCDEF” at every 100th line of a file?
sed ‘100iABCDEF’ file1

Q. Write a command sequence to find all the files modified in less than 2 days and print the record count of each.
find . –mtime -2 –exec wc –l {} ;

Q. How can I set the default rwx permission to all users on  every file which is created in the current shell?
We can use:
1    umask 777
This will set default rwx permission for every file which is created to every user.

Q. How can we find the process name from its process id?
We can use “ps –p ProcessId”

Q. What are the four fundamental components of every file system on linux?
bootblock, super block, inode block and  datablock

Q. What is a boot block?
This block contains a small program called “Master Boot record”(MBR) which loads the kernel  during system boot up.

Q. What is a super block?
Super block contains all the information about the file system like size of file system, block size used by it,number of free data blocks and list of free inodes and data blocks.

Q. What is an inode block?
This block contains the inode for every file of the file system along with all the file attributes except its name.

Q. How can I send a mail with a compressed file as an attachment?
zip file1|mailx –s “subject” Recepients email id
Email content

Q. How do we create command aliases in shell?
alias Aliasname=”Command whose alias is to be created”

Q. What are “c” and “b” permission fields of a file?
“c “ and “b” permission fields are generally associated with a device file. It specifies whether a file is a character special file or a block special file.

Q. What is the use of a shebang line?
Shebang line at top of each script determines the location of the engine which is to be used in order to execute the script.


Explore Unix Shell Scripting Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules