Sunday, 17 April 2016

Shell script : Interview Questions


Q. What is the output if execute ./temp.sh
temp.sh
#!/bin/bash
./temp1.sh
echo Hello

temp1.sh
#!/bin/bash
exit 1

Answer.
Exit from temp1.sh will lead to exit from script and print nothing.


Q. What is difference between : 
a) echo "Good      morning"
b) echo Good      morning

Answer.
Double quotes print spaces (in between) while without double quote will print a single space instead of many spaces.


Q. exit -1 vs. exit 1
Answer. When exit command returns any value other than 0 (zero), the script will throw an error and will abort.
0 (zero) represents successful execution.
exit -1 or exit 1 (without quotes) before script termination will abort the script.


Q. How to remove first line (header) from a file ?
Answer.  # sed '1 d' file.txt


Q. How to check if a file or directory exists or not ?
Answer.
if [ -f $myfile ]
then
   echo "$myfile exists"
fi

Flag -d checks the directory exists or not.


Q. If I try to un mount a file system it say’s resource is busy.
# umount /mnt/dir
How you check what is the problem ?
(Here, ps command is giving no clue to you)

Answer.
1. Try fuser which will tell you which processes are accessing the mount point.
# fuser -vm /mnt/dir
Then, you can use ps command to find the process

2. Try lsof command which shows each open file on the mount.
# lsof /mnt/dir
# lsof | grep '/mnt/dir'


Q. How to display the shell's environment variables ?
$ env


Q. How to start running a process in background ?
$ ./process-name &


Q. How to find out the number of arguments passed to the shell script ?
Use ?#


Q. How to refer to the arguments passed to a shell script ?
Use $0 for script name
Use $1, $2, $3 .... $n  for arguments passed to script

No comments:

Post a Comment

Note: only a member of this blog may post a comment.