Real shell scripting interview questions

Q What is Shell?

Ans: Shell is a command interpreter, which interprets the command which the user gives to the kernel. It can also be defined as an interface between a user and operating system.

Q How to debug the problems encountered in shell script/program?

Ans: Two options
1) Execute the script as “sh -x script.sh”
2) Put “set -x” in the script

Q Which is the symbol used for comments in bash shell scripting ?
Ans:

#

Q What is the difference between = and ==?

Ans:

=      -> It is used for assigning value to the variable.

==    -> It is used for string comparison.

Q How to get 4th element from each line of a file ?

Ans:

awk '{print $4}'

Q What needs to be done before you can execute a shell script?

Ans:
You need to make the shell script executable using the chmod command.

This chmod command makes the shell script file “file1” executable for the user (owner) only:
$ chmod u+x file1

Below syntax makes it executable for all (everyone):

$ chmod a+x file1

Q How to pass argument to a script ?
Ans:

./script argument

Q How do you terminate an if statement?

Ans: Using “fi” . Check example below.

Q Give an example of if else statement
Ans:

#Testfile.sh script to test if the file exists#!/bin/kshcvfile=$1if [ -f $cvfile ]thenecho "$cvfile exists"else"$cvfile does not exists"fiexit 0

So you will execute the script as “./Testfile.sh file1” .

Q How to check if a directory exists?

Ans:

if [ -d $mydir ] thenecho "Directory exists"fi

Q How to calculate number of passed arguments ?

Ans:

$#

Q How to check if previous command run successful ?

Ans:

echo $?

If exit code is 0 it means command ran successfully

Q How to get last line from a file ?

Ans:

tail -1

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

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

Q How to remove blank lines from a file?

Ans :

grep -v '^

Q Write a command to find all the files modified in less than 3 days and print the record count of each?

find . –mtime -3 –exec wc –l {} \;

Q How to find a process name from process ID?

ps -p PID

 testcv.txt > testcv2.txt

Q Write a command to find all the files modified in less than 3 days and print the record count of each?

find . –mtime -3 –exec wc –l {} \;

Q How to find a process name from process ID?

ps -p PID

No comments:

Post a Comment