Thursday 7 September 2017

Shell Scripting Interview Questions and Answer

Shell Scripting Interview Questions and Answer

Question: How to Check if a directory exist?
DIRECTORY='directoryname'
if [ -d "$DIRECTORY" ]; then
  echo "Directory is found"
else
  echo "Directory is Not found"
fi



Question: How to concatenate two string variable?
str1='Web'
str2='Technology'
fullStr="$str1 $str2";
echo $fullStr; #Web Technology 



Question: What do you mean by echo file1.txt > file2.txt?
> is used to redirect output.
echo file1.txt > file2.txt

It just redirect the output to file2.txt


Question: What do you means by 2>&1?
0 is stdin
1 is stdout
2 is stderr
>& is the syntax to redirect a stream to another file descriptor

So, Its saying display the error on stdout


Following two do same thing.
echo test 1>&2
OR
echo test >&2




Question: What is scp and why use? Give example?
SCP is used to copy the file/dir from one server to another server.
Example:
scp -r user@your.server.example.com:/path/to/source /home/user/destination/




Question: What is command to copy a file?
cp file1.txt \another\folder\file1.txt



Question: What is command to move a file?
mv file1.txt \another\folder\file1.txt



Question: How to count number of words in file?
 wc -w file.txt



Question: How to append in file from source file?
 cat sourcefile.txt >> destinationfile.txt
It will add the content in destinationfile.txt from sourcefile.txt



Question: How to search a string and then delete that line?
 sed '/removeTxt/d' ./file
It will remove the line having content removeTxt and print the output to console.



Question: How to set a variable to the output from a command?
 OUTPUT="$(ls -1)"
echo "${OUTPUT}"



Question: How to convert a string in lowercase?
a="Hello World!" 
echo "$a" | tr '[:upper:]' '[:lower:]' #hello world!



Question: What is use of export command?
export command is used to make the available of variable in child process.
Example 
export name=test

Now name variable will be accessible in child process.



Question: How to print date in yyyy-mm-dd format?
YYYY-MM-DD format
echo `date +%Y-%m-%d`
YYYY-MM-DD HH:MM:SS format
echo `date '+%Y-%m-%d %H:%M:%S'`



Question: How to reverse the lines?
tac file1.txt
It will revere the lines and display in console output.


Question: How to redirect output to file?
 ls -l 2>&1 | tee -a errorfile.txt

It will store error and output(both) in error_file.txt


Question: How to determine whether a Linux is 32 bit or 64 bit?
uname -m

Output
x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel



Question: How to compare two directories?
diff --brief -r dir1/ dir2/
diff -qr -r dir1/ dir2/



Question: When do we need curly braces around shell variables?
When you want to expand the variable (like foo) in the string.
For Example you want to make $foobar.
echo "${foo}bar"