# Unix Shell Scripting Interview Questions

## unix shell scripting Interview Questions

### 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

### 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

### @ 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.

### while ($n) ### # actions ### … ### end ### 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:

#!/bin/csh

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)

### @ 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

endif

end

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 ### versus ### #!/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} ### and ### 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}}

or

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

endif

### 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

### 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

### 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’

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

#!/bin/csh

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 endif 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++

end

or,

set myarray = (value1, value2, value3, value4, value5)

set i = 1

### 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”

else

### echo $fl:h ### What do you expect to be displayed? txt fs_report1 fs_report1.txt /home/dbuser5/reports ### 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

continue

endif

mv $my_old_file1$my_new_ file1

end

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

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:

$# 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) Eg:  1 2 3 4if cat file1 ABCD EFGH Then O/p should be EFGH ABCD  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.

 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 2 3tr –s “(backslash)040” <file1|tr –s “(backslash)011”|tr “(backslash)040 (backslash)011” “(backslash)012” |uniq –c where “(backslash)040” is octal equivalent of “space” ”(backslash)011” is octal equivalent of “tab character” and “(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 ### 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.

### 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

>bye

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

>Write the command to execute

>quit

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

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23#!/bin/sh

a=1

b=1

echo $a echo$b

for I in 1 2 3 4 5 6 7 8

do

c=a

b=$a b=$(($a+$c))

### 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

Syntax:

for  iterator in (elements)

do

execute commands

done

### 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?

Syntax

If  condition is successful

then

execute commands

else

execute commands

fi

### 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 ‘100i\ABCDEF’ 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:

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.zip file1|mailx –s “subject” Recepients email id

Email content

EOF

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