Interview Q&A for Shell Script Part-II


Q21:-What difference between & and &&
Ans:-
& - we using it when want to put script to background
&& - when we wand to execute command/script if first script was finished successfully

Q22:-When we need "if" before [ condition ] ?
Ans:-When we need to run several commands if condition meets.

Q23:- What would be the output of the command: name=John && echo 'My name is $name'? Ans:-My name is $name

Q24:- Which is the symbol used for comments in bash shell scripting ? 
Ans:-#

Q25:- What would be the output of command: echo ${new:-variable} 
Ans:- variable

Q26:- What difference between ' and " quotes ?
 Ans:-
' - 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.

Q27:-How to redirect stdout and stderr streams to log.txt file from script inside ?
Ans:-Add "exec >log.txt 2>&1" as the first command in the script

Q28:-How to get part of string variable with echo command only ? 
Ans:-
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

Q29:-How to get home/dir with echo command only if string variable="User:123:321:/home/dir" is given ? 
Ans:-
echo ${variable#*:*:*:}
or
echo ${variable##*:}

Q30:-How to get “User” from the string above ?
Ans:- echo ${variable%:*:*:*}
or
echo ${variable%%:*}

Q31:- How to list users which UID is greater then 500 (awk) ? 
Ans:- awk -F: '$3>500' /etc/passwd

Q32:-Write the program which counts unique primary groups for users and displays count and group name only 
Ans:-
cat /etc/passwd|cut -d: -f4|sort|uniq -c|while read c g
do
{ echo $c; grep :$g: /etc/group|cut -d: -f1;}|xargs -n 2
done

Q33:-How to change standard field separator to ":" in bash shell ? 
Ans:- By setting the value of IFS (Input Field Seprator)
IFS=":"

Q34:-How to get variable length ? 
Ans:- ${#variable}

Q35:-How to print last 5 characters of variable ? 
Ans:- echo ${variable: -5}

Q36:-What difference between ${variable:-10} and ${variable: -10} ?
 Ans:-
${variable:-10} - gives 10 if variable was not assigned before
${variable: -10} - gives last 10 symbols of variable

Q37:-How to substitute part of string with echo command only ? 
Ans:- echo ${variable//pattern/replacement}

Q38:-Which command replaces string to uppercase ? 
Ans:- tr (Translate) command is used
tr '[:lower:]' '[:upper:]'

Q39:-How to count local accounts ? 
Ans:-
wc -l /etc/passwd|cut -d" " -f1
or
cat /etc/passwd|wc -l

Q40:-How to count words in a string without wc command ? 
Ans:-
set ${string}
echo $#

No comments:

Post a Comment