Showing posts with label Shell Script. Show all posts
Showing posts with label Shell Script. Show all posts

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"




Wednesday, 6 September 2017

Unix Shell Scripting Tutorial - page 8

Unix Shell Scripting Tutorial - page 8

Question: What are two different way to executing a file?
Script file with name script8.sh
myname='Arun kumar';
echo $myname 

Way #1
sh script8.sh

After executing this script, if we run echo $myname it will not print anything because $myname is not in scope.

Way #2
source script8.sh

After executing this script, if we run echo $myname it will print because $myname is in scope.


Question: How to get input from user?
echo "Enter your name?"
read name
echo "Your name is '$name'"



Question: How to include configuration file in main file?
use source to include file.
source config.sh
myname='Arun kumar';
echo $myname 



Question: Give example of for?
for  table in {2..20..2}
do 
echo "$table,"
done

Output 2,4,6,8,10,12,14,16,18,20


Question: What is difference between while and until?
 Until loop always executes at least once. while executes till it returns a zero value and until loop executes till it returns non-zero value.

Question: Give example of function with parameters?
function fname(){
    echo $1; #first argument
    echo $2; #second argument
    echo $3; #third argument
}

fname a b c


Question: Give example of Switch case?
FRUIT="kiwi"

case "$FRUIT" in
   "apple") echo "Apple is good for health." 
   ;;
   
   "banana") echo "I like banana." 
   ;;
   
   "kiwi") echo "New Zealand is famous for kiwi fruit." 
   ;;
esac


Question: What does do eval? Give example eval
execute the statement.
name='name_variable'
name_variable='This is value'
echo $name; #name_variable
echo \${$name}; #${name_variable}
eval echo \${$name}; #This is value

Monday, 4 September 2017

Unix Shell Scripting Tutorial - page 7

Unix Shell Scripting Tutorial - page 7

Question: What is meaning of first line in unix?
#!/bin/bash

This indicates that the script should be run in the bash shell regardless of which interactive shell.


Question: What sign is used in unix for comment a line?
Pound Sign

Pound sign (#), is used to comment a line.

# echo "this is comment" 



Question: When to use single quote OR Double quote?
Single quote: When you are assigning string without variable, then you should use single quote.
Double quote: When you are assigning string with variable, then you should use Double quote.


Question: What's wrong in following variable?
strVar = "Hello World! How are you?" 
echo $strVar;

There should not be space before and after the equal sign (=). Correct code are below:
strVar="Hello World! How are you?" 
echo $strVar;



Question: Give sample example of If else?
if condition1
then
 statement1
 statement2
 statement3
 
else
 statement4
 statement5
fi



Question: Give sample example of If elseif?
if condition1
then
 statement1
 statement2
 statement3
 
elif condition2
then
 statement4
 statement5
 
elif condition3
then
 statement6
 statement7
 statement8
fi



Question: Give list of Operator used in unix shell scripting?
Operator Results number of operands
-noperand non zero length1
-zoperand has zero length1
-dthere exists a directory whose name is operand1
-fthere exists a file whose name is operand1
-eqthe operands are integers and they are equal2
-neqthe opposite of -eq2
=the operands are equal (as strings)2
!=opposite of = 2
-ltoperand1 is strictly less than operand2 (both operands should be integers)2
-gtoperand1 is strictly greater than operand2 (both operands should be integers)2
-geoperand1 is greater than or equal to operand2 (both operands should be integers)2
-leoperand1 is less than or equal to operand2 (both operands should be integers)2



Friday, 1 September 2017

Unix Shell Scripting Tutorial - page 6

Unix Shell Scripting Tutorial - page 6

Question: How can we search in file using Regular expression?
We use grep command.
grep "search string" filename.txt



Question: How to search a string in file?
grep "search string" filename.txt

search string is text searched in filename.txt. By Default its case sensitive.


Question: How to search a case-insensitive string in file?
use -i to search case insensitive.
grep -i "search string" filename.txt



Question: How to search a string in mutiple file?
separate the filename by space.
grep -i "search string" filename.txt filename2.txt filename3.txt 



Question: How to search a string in file using regular expression? Use regex character for example .* used to search all
grep -i "textname .*" filename.txt 

It will return all after the textname.


Question: What are the basic Regex characters?
  1. ? The preceding item is optional and matched at most once.
  2. * matched zero or more times.
  3. + matched one or more times.
  4. {n} matched exactly n times.
  5. {n,} matched n or more times.
  6. {,m} matched at most m times.
  7. {n,m} matched at least n times, but not more than m times.



Question: How to search a words in file?
Use -w to search words.
grep -iw "textname" filename.txt 

It will not search textnameA.


Question: How to search and return next line?
grep -A 3 -i "textname" filename.txt

It will search and return next 3 lines after search.
You can use -B to return Before 3 lines.


Question: How to search recursively in folder? Use -r to search recursive.
grep -r "textname" 



It will search in current folder and sub-folder.


Question: How to find number of matches ? Use -c to return number of matches.
grep -c "textname" fiename.txt

It will return number of matches in number.


Question: What are the Performance Tools in unix?
  1. nice/renice: Runs a program with modified scheduling priority.
  2. netstat: Prints network connections, routing tables and interface statistics.
  3. time: give resource usage
  4. uptime: This is System Load Average.
  5. ps: Current process list
  6. vmstat: Virtual Memory stats
  7. top: Top Task List



Question: What is syslog?
Syslog is a way for network devices to send event messages to a server. Also known as Syslog server.
SysLog is stored in /etc/syslogd OR /etc/syslog.
syslog.conf have following configuration.
*.err;kern.debug;auth.notice /dev/console
daemon,auth.notice           /var/log/messages
lpr.info                     /var/log/lpr.log
mail.*                       /var/log/mail.log
ftp.*                        /var/log/ftp.log
mark.*                       /dev/console



Question: What is command for logging?
logger [-i] [-f file] [-p priority] [-t tag] [message]



Thursday, 31 August 2017

Unix Shell Scripting Tutorial - page 5

Unix Shell Scripting Tutorial - page 5

Question: What are the directory structure of unix?
  1. /: This is the root directory which should contain only the directories.
  2. /bin: Executable files are located here.
  3. /dev: Device drivers
  4. /etc: configuration files, valid user lists, groups, ethernet and hosts etc
  5. /lib: shared library files and sometimes other kernel-related files.
  6. /boot: files for booting the system.
  7. /home: home directory for users and other accounts
  8. /mnt: Used to mount other temporary file systems like CD/pendrive
  9. /proc: Contains all processes marked as a file by process number.
  10. /tmp: Holds temporary files used between system boots.
  11. /user: Used for miscellaneous purposes.
  12. /var: Typically contains log and print files.
  13. /sbin: Contains binary (executable) files.
  14. /kernel: kernel files



Question: How to create a new Group?
groupadd mynewgroup



Question: How to modify group name?
groupmod -n new_modified_group_name old_group_name



Question: How to delete group?
groupdel new_modified_group_name



Question: How to add a existing user to a group?
usermod -a -G mynewgroup username

-G Its for secondary group.
-g Its for primary group.


Question: How to change a User's Primary Group?
usermod -g groupname username  



Question: How to list groups of loggined user?
groups



Question: How to list groups of other user?
groups username



Question: How to Create a New User and Assign a Group?
useradd -G examplegroup username



Question: How to assign a user multiple groups?
usermod -a -G group1,group2,group3 username