100+ Interview Questions and Answers for Shell Scripting

1. How will you abort a shell script before it is successfully executed?

Answer : We need to use ‘exit’ command to fulfil the above described situation. A ‘exit’ command when forced to output any value other than 0 (zero), the script will throw an error and will abort. The value 0 (zero) under Unix environment shell scripting represents successful execution. Hence putting ‘exit -1’, without quotes before script termination will abort the script.

For example, create a following shell script as ‘anything.sh‘.

#!/bin/bash

echo “Hello”

exit -1

echo “bye”

Save the file and execute it.

# sh anything.sh

Hello

exit.sh: 3: exit: Illegal number: -1

From the above script, it is clear that the execution went well before exit -1 command.

2. How to remove the headers from a file using command in Linux?

Answer : A ‘sed’ command comes to rescue here, when we need to delete certain lines of a file.

Here it the exact command to remove headers from a file (or first line of a file).

# sed ‘1 d’ file.txt

The only problem with above command is that, it outputs the file on standard output without the first line. In order to save the output to file, we need to use redirect operator which will redirects the output to a file.

# sed ‘1 d’ file.txt > new_file.txt

Well the built in switch ‘-i‘ for sed command, can perform this operation without a redirect operator.

# sed -i ‘1 d’ file.txt

3. How will you check the length of a line from a text file?

Answer : Again ‘sed’ command is used to find or check the length of a line from a text file.

A ‘sed –n ‘n p’ file.txt‘, where ‘n‘ represents the line number and ‘p‘ print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. So, how to get the length count? Obviously! we need to pipeline the output with ‘wc‘ command.

# sed –n ‘n p’ file.txt | wc –c

To get the length of line number ‘5’ in the text file ‘tecmint.txt‘, we need to run.

# sed -n ‘5 p’ tecmint.txt | wc -c

4. Is it possible to view all the non-printable characters from a text file on Linux System? How will you achieve this?

Answer : Yes! it is very much possible to view all the non-printable characters in Linux. In order to achieve the above said scenario, we need to take the help of editor ‘vi’.

How to show non-printable characters in ‘vi‘ editor?

  1. Open vi editor.
  2. Go to command mode of vi editor by pressing [esc] followed by ‘:’.
  3. The final step is to type execute [set list] command, from command interface of ‘vi’ editor. ( set number – to number each lines of files)

Note: This way we can see all the non-printable characters from a text file including ctrl+m (^M).

5. You are a Team-Leader of a group of staffs working for a company xyz. The company ask you to create a directory ‘dir_xyz’, such that any member of the group can create a file or access a file under it, but no one can delete the file, except the one created it. what will you do?

Answer : An interesting scenario to work upon. Well in the above said scenario we need to implement the below steps which is as easy as cake walk.

# mkdir dir_xyz

# chmod g+wx dir_xyz

# chmod +t dir_xyz

The first line of command create a directory (dir_xyz). The second line of command above allow group (g) to have permission to ‘write‘ and ‘execute‘ and the last line of the above command – The ‘+t‘ in the end of the permissions is called the ‘sticky bit‘. It replaces the ‘x‘ and indicates that in this directory, files can only be deleted by their owners, the owner of the directory or the root superuser.

6. Can you tell me the various stages of a Linux process, it passes through?

Answer : A Linux process normally goes through four major stages in its processing life.

Here are the 4 stages of Linux process.

  1. Waiting: Linux Process waiting for a resource.
  2. Running : A Linux process is currently being executed.
  3. Stopped : A Linux Process is stopped after successful execution or after receiving kill signal.
  4. Zombie : A maProcess is said to be ‘Zombie’ if it has stopped but still active in process table.

7. What is the use of cut command in Linux?

Answer : A ‘cut’ is a very useful Linux command which proves to be helpful when we need to cut certain specific part of a file and print it on standard output, for better manipulation when the field of the file and file itself is too heavy.

For example, extract first 10 columns of a text file ‘txt_tecmint‘.

# cut -c1-10 txt_tecmint

To extract 2nd, 5th and 7th column of the same text file.

# cut -d;-f2 -f5 -f7 txt_tecmint

8. What is the difference between commands ‘cmp’ and ‘diff’?

Answer : The command ‘cmp’ and ‘diff’ means to obtain the same thing but with different mindset.

The ‘diff‘ command reports the changes one should make so that both the files look the same. Whereas ‘cmp‘ command compares the two files byte-by-byte and reports the first mismatch.

9. Is it possible to substitute ‘ls’ command with ‘echo’ command?

Answer : Yes! the ‘ls’ command can be substituted by ‘echo’ command. The command ‘ls’ lists the content of file. From the point of view of replacement of above command we can use ‘echo *’, obviously without quotes. The output of both the commands are same.

10. You might have heard about inodes. can you describe inode briefly?

Answer : A ‘inode’ is a ‘data-structure’, which is used for file identification on Linux. Each file on an Unix System has a separate ‘inode’ and an ‘Unique’ inode Number.

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

12: 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” .

13: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”

14:What is the difference between soft and hard links?

Soft links are link to the file name however hard links are link to the inode 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)

15: 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

16: What is the significance of $#?

$# shows the count of the arguments passed to the script.

17: 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.

18: Given a file,  replace all occurrence of word “ABC” with “DEF” from 5th line till end in only those lines that contains word “MNO”

sed –n ‘5,$p’ file1|sed ‘/MNO/s/ABC/DEF/’

 

19: How will you find the 99th line of a file using only tail and head command?

tail +99 file1|head -1

20: Print the 10th line without using tail and head command.

1 sed –n ‘10p’ file1

 

21: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.

22: 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.

23: How can you find out how long the system has been running?

Command “uptime”

24: 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.

25: 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.

26: 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.

27: 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.

28: I want to connect to a remote server and execute some commands, how can I achieve this?

We can use ssh to do this:

ssh username@serverIP -p sshport

Example

ssh root@122.52.251.171 -p 22

Once above command is executed, you will be asked to enter password

29: 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.

30: 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

31: What are the 3 standard streams in Linux?

0 – Standard Input
1 – Standard Output
2 – Standard Error

32: Given a file find the count of lines containing word “ABC”.

grep –c  “ABC” file1

33: 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)

34: Write down the syntax of “for “ loop

Syntax:

for  iterator in (elements)

do

execute commands

done

35: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.

36: Write the syntax for “if” conditionals in linux?

Syntax

If  condition is successful

then

execute commands

else

execute commands

fi

37:What is the significance of $? ?

$? gives the exit status of the last command that was executed.

38: 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

39: How will I insert a line “ABCDEF” at every 100th line of a file?

sed ‘100i\ABCDEF’ file1

40: 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 {} \;

41: 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.

42: How can we find the process name from its process id?

We can use “ps –p ProcessId”

43: 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

44: 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.

45: How do you terminate a shell script if statement?
With fi, which is “if” spelled backwards.

46: What UNIX operating system command would you use to display the shell’s environment variables?
Running the “env” command will display the shell environment variables.
47: What code would you use in a shell script to determine if a directory exists?
The UNIX test command with the -d option can be used to determine if a directory exists.

Details:
The following test command expression would be used to verify the existence of a specified directory, which is stored in the variable $mydir:
if [ -d $mydir ]
then
command(s)
fi

48: How do you access command line arguments from within a shell script?
Arguments passed from the command line to a shell script can be accessed within the shell script by using a $ (dollar sign) immediately followed with the argument’s numeric position on the command line.

Details:
For example, $1 would be used within a script to access the first argument passed from the command line, $2 the second, $3 the third and so on. Bonus: $0 contains the name of the script itself.
49: What does 2>&1 mean and when is it typically used?
The 2>&1 is typically used when running a command with its standard output redirected to a file. For example, consider:

command > file 2>&1

Anything that is sent to command’s standard output will be redirected to “file” in this example.

The 2 (from 2>&1) is the UNIX file descriptor used by standard error (stderr). Therefore, 2>&1 causes the shell to send anything headed to standard error to the same place messages to standard output (1) are sent…which is “file” in the above example.

To make this a little clearer, the > in between “command” and “file” in the example is equivalent to 1>.

50: Within a UNIX shell scripting loop construct, what is the difference between the break and continue?
Using break within a shell scripting loop construct will cause the entire loop to terminate. A continue will cause the current iteration to terminate, but the loop will continue on the next iteration.

51: How to pass argument to a script ?

./script argument

Example : Script will show filename

./show.sh file1.txt

cat show.sh
#!/bin/bash
cat $1

52: How to calculate number of passed arguments ?

$#

53: How to get script name inside a script ?

$0

54: How to check if previous command run successful ?

$?

55: How to get last line from a file ?

tail -1

56: How to get first line from a file ?

head -1

57: How to get 3rd element from each line from a file ?

awk ‘{print $3}’

58: How to get 2nd element from each line from a file, if first equal FIND

awk ‘{ if ($1 == “FIND”) print $2}’

59: Give an example how to write function ?

function example {
echo “Hello world!”
}

60: How to check if file exist on filesystem ?

if [ -f /var/log/messages ] then
echo “File exists”
fi

61: Write down syntax for all loops in shell scripting ?

for loop :

for i in $( ls ); do
echo item: $i
done

while loop :

#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done

until loop :

#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done

62: What it means by #!/bin/sh or #!/bin/bash at beginning of every script ?

That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there there will be #!/usr/bin/python

63: How to get 10th line from the text file ?

head -10 file|tail -1

64: What is the first symbol in the bash script file

#

65: What command “export” do ?

Makes variable public in subshells

66: How to run script in background ?

add “&” to the end of script

67: What “chmod 500 script” do ?

Makes script executable for script owner

68: What “>” do ?

Redirects output stream to file or another stream.

69: What difference between & and &&

& – we using it when want to put script to background
&& – when we wand to execute command/script if first script was finished successfully

70: When we need “if” before [ condition ] ?

When we need to run several commands if condition meets.

71: What difference between ‘ and ” quotes ?

‘ – we use it when do not want to evaluate variables to the values
” – all variables will be evaluated and its values will be assigned instead.

72: How to redirect stdout and stderr streams to log.txt file from script inside ?

Add “exec >log.txt 2>&1” as the first command in the script

73: How to get part of string variable with echo command only ?

echo ${variable:x:y}
x – start position
y – length
example:
variable=”My name is Petras, and I am developer.”
echo ${variable:11:6} # will display Petras

74: How to get variable length ?

${#variable}

75: How to print last 5 characters of variable ?

echo ${variable: -5}

76: How to substitute part of string with echo command only ?

echo ${variable//pattern/replacement}

77: Which command replaces string to uppercase ?

tr ‘[:lower:]’ ‘[:upper:]’

78: How to count local accounts ?

wc -l /etc/passwd|cut -d” ” -f1
or
cat /etc/passwd|wc -l

79: How to count words in a string without wc command ?

set ${string}
echo $#

80: Which one is correct “export $variable” or “export variable” ?

export variable

81: How to list files where second letter is a or b ?

ls -d ?[ab]*

82: How to remove all spaces from the string ?

echo $string|tr -d ” ”

83: Write the command which will print numbers from 0 to 100 and display every third (0 3 6 9 …) ?

for i in {0..100..3}; do echo $i; done
or
for (( i=0; i<=100; i=i+3 )); do echo “Welcome $i times”; done

84: How to print all arguments provided to the script ?

echo $*
or
echo $@

85: What difference between [ $a == $b ] and [ $a -eq $b ]

[ $a == $b ] – should be used for string comparison
[ $a -eq $b ] – should be used for number tests

86: What difference between = and ==

= – we using to assign value to variable
== – we using for string comparison

87: Write the command to test if $a greater than 12 ?

[ $a -gt 12 ]

88: Write the command to test if $b les or equal 12 ?

[ $b -le 12 ]

89: How to check if string begins with “abc” letters ?

[[ $string == abc* ]]

90: What difference between [[ $string == abc* ]] and [[ $string == "abc*” ]]

[[[[ $string == abc* ]– will check if string begins with abc letters
[[[[ $string == "abc*” ]– will check if string is equal exactly to abc*

91: How to list usernames which starts with ab or xy ?

egrep “^ab|^xy” /etc/passwd|cut -d: -f1

92: What $! means in bash ?

Most recent background command PID

93: What $? means ?

Most recent foreground exit status.

94: How to print PID of the current shell ?

echo $$

95: How to get number of passed arguments to the script ?

echo $#

96: What difference between $* and $@

$* – gives all passed arguments to the script as a single string
$@ – gives all passed arguments to the script as delimited list. Delimiter $IFS

97: How to define array in bash ?

array=(“Hi” “my” “name” “is”)

98: How to print the first array element ?

echo ${array[0]}[0]>

99: How to print all array elements ?

echo ${array[@]}[@]>

100: How to print all array indexes ?

echo ${!array[@]}[@]>

101: How to remove array element with id 2 ?

unset array[2]<[2]

102: How to add new array element with id 333 ?

array[333[333]New_element”

103: How shell script get input values ?

a) via parameters

./script param1 param2

b) via read command

read -p “Destination backup Server : ” desthost

104:  How can we use “expect” command in a script ?

/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect “*?assword:*”
send “${password}\r”
expect eof
EOD

Leave a Reply

Your email address will not be published. Required fields are marked *