[Translated] tech/20150518 70 Expected Shell Scripting Interview Questions and Answers

This commit is contained in:
ictlyh 2015-05-18 19:33:45 +08:00
parent c7cd7b425d
commit df159f8699
2 changed files with 399 additions and 400 deletions

View File

@ -1,400 +0,0 @@
Translating by ictlyh
70 Expected Shell Scripting Interview Questions & Answers
================================================================================
We have selected expected 70 shell scripting question and answers for your interview preparation. Its really vital for all system admin to know scripting or atleast the basics which in turn helps to automate many tasks in your work environment. In the past few years we have seen that all linux job specification requires scripting skills.
### 1) How to pass argument to a script ? ###
./script argument
**Example** : Script will show filename
./show.sh file1.txt
cat show.sh
#!/bin/bash
cat $1
### 2) How to use argument in a script ? ###
First argument: $1,
Second argument : $2
Example : Script will copy file (arg1) to destination (arg2)
./copy.sh file1.txt /tmp/
cat copy.sh
#!/bin/bash
cp $1 $2
### 3) How to calculate number of passed arguments ? ###
$#
### 4) How to get script name inside a script ? ###
$0
### 5) How to check if previous command run successful ? ###
$?
### 6) How to get last line from a file ? ###
tail -1
### 7) How to get first line from a file ? ###
head -1
### 8) How to get 3rd element from each line from a file ? ###
awk '{print $3}'
### 9) How to get 2nd element from each line from a file, if first equal FIND ###
awk '{ if ($1 == "FIND") print $2}'
### 10) How to debug bash script ###
Add -xv to #!/bin/bash
Example
#!/bin/bash xv
### 11) Give an example how to write function ? ###
function example {
echo "Hello world!"
}
### 12) How to add string to string ? ###
V1="Hello"
V2="World"
V3=$V1+$V2
echo $V3
Output
Hello+World
### 13) How to add two integers ? ###
V1=1
V2=2
V3=$V1+$V2
echo $V3
Output
3
### 14) How to check if file exist on filesystem ? ###
if [ -f /var/log/messages ]
then
echo "File exists"
fi
### 15) Write down syntax for all loops in shell scripting ? ###
#### for loop : ####
for i in $( ls ); do
echo item: $i
done
#### while loop : ####
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
until l#### ####oop :
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
### 16) What it means by #!/bin/sh or #!/bin/bash at beginning of every script ? ###
That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there there will be #!/usr/bin/python
### 17) How to get 10th line from the text file ? ###
head -10 file|tail -1
### 18) What is the first symbol in the bash script file ###
#
### 19) What would be the output of command: [ -z "" ] && echo 0 || echo 1 ###
0
### 20) What command "export" do ? ###
Makes variable public in subshells
### 21) How to run script in background ? ###
add "&" to the end of script
### 22) What "chmod 500 script" do ? ###
Makes script executable for script owner
### 23) What ">" do ? ###
Redirects output stream to file or another stream.
### 24) What difference between & and && ###
& - we using it when want to put script to background
&& - when we wand to execute command/script if first script was finished successfully
### 25) When we need "if" before [ condition ] ? ###
When we need to run several commands if condition meets.
### 26) What would be the output of the command: name=John && echo 'My name is $name' ###
My name is $name
### 27) Which is the symbol used for comments in bash shell scripting ? ###
#
### 28) What would be the output of command: echo ${new:-variable} ###
variable
### 29) What difference between ' and " quotes ? ###
' - 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.
### 30) How to redirect stdout and stderr streams to log.txt file from script inside ? ###
Add "exec >log.txt 2>&1" as the first command in the script
### 31) How to get part of string variable with echo command only ? ###
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
### 32) How to get home_dir with echo command only if string variable="User:123:321:/home/dir" is given ? ###
echo ${variable#*:*:*:}
or
echo ${variable##*:}
### 33) How to get “User” from the string above ? ###
echo ${variable%:*:*:*}
or
echo ${variable%%:*}
### 34) How to list users which UID less that 100 (awk) ? ###
awk -F: '$3<100' /etc/passwd
### 35) Write the program which counts unique primary groups for users and displays count and group name only ###
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
### 36) How to change standard field separator to ":" in bash shell ? ###
IFS=":"
### 37) How to get variable length ? ###
${#variable}
### 38) How to print last 5 characters of variable ? ###
echo ${variable: -5}
### 39) What difference between ${variable:-10} and ${variable: -10} ? ###
${variable:-10} - gives 10 if variable was not assigned before
${variable: -10} - gives last 10 symbols of variable
### 40) How to substitute part of string with echo command only ? ###
echo ${variable//pattern/replacement}
### 41) Which command replaces string to uppercase ? ###
tr '[:lower:]' '[:upper:]'
### 42) How to count local accounts ? ###
wc -l /etc/passwd|cut -d" " -f1
or
cat /etc/passwd|wc -l
### 43) How to count words in a string without wc command ? ###
set ${string}
echo $#
### 44) Which one is correct "export $variable" or "export variable" ? ###
export variable
### 45) How to list files where second letter is a or b ? ###
ls -d ?[ab]*
### 46) How to add integers a to b and assign to c ? ###
c=$((a+b))
or
c=`expr $a + $b`
or
c=`echo "$a+$b"|bc`
### 47) How to remove all spaces from the string ? ###
echo $string|tr -d " "
### 48) Rewrite the command to print the sentence and converting variable to plural: item="car"; echo "I like $item" ? ###
item="car"; echo "I like ${item}s"
### 49) Write the command which will print numbers from 0 to 100 and display every third (0 3 6 9 …) ? ###
for i in {0..100..3}; do echo $i; done
or
for (( i=0; i<=100; i=i+3 )); do echo "Welcome $i times"; done
### 50) How to print all arguments provided to the script ? ###
echo $*
or
echo $@
### 51) What difference between [ $a == $b ] and [ $a -eq $b ] ###
[ $a == $b ] - should be used for string comparison
[ $a -eq $b ] - should be used for number tests
### 52) What difference between = and == ###
= - we using to assign value to variable
== - we using for string comparison
### 53) Write the command to test if $a greater than 12 ? ###
[ $a -gt 12 ]
### 54) Write the command to test if $b les or equal 12 ? ###
[ $b -le 12 ]
### 55) How to check if string begins with "abc" letters ? ###
[[ $string == abc* ]]
### 56) What difference between [[ $string == abc* ]] and [[ $string == "abc* ]] ###
[[ $string == abc* ]] - will check if string begins with abc letters
[[ $string == "abc*"" ]] - will check if string is equal exactly to abc*
### 57) How to list usernames which starts with ab or xy ? ###
egrep "^ab|^xy" /etc/passwd|cut -d: -f1
### 58) What $! means in bash ? ###
Most recent background command PID
### 59) What $? means ? ###
Most recent foreground exit status.
### 60) How to print PID of the current shell ? ###
echo $$
### 61) How to get number of passed arguments to the script ? ###
echo $#
### 62) What difference between $* and $@ ###
$* - gives all passed arguments to the script as a single string
$@ - gives all passed arguments to the script as delimited list. Delimiter $IFS
### 63) How to define array in bash ? ###
array=("Hi" "my" "name" "is")
### 64) How to print the first array element ? ###
echo ${array[0]}
### 65) How to print all array elements ? ###
echo ${array[@]}
### 66) How to print all array indexes ? ###
echo ${!array[@]}
### 67) How to remove array element with id 2 ? ###
unset array[2]
### 68) How to add new array element with id 333 ? ###
array[333]="New_element"
### 69) How shell script get input values ? ###
a) via parameters
./script param1 param2
b) via read command
read -p "Destination backup Server : " desthost
### 70) How can we use "expect" command in a script ? ###
/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect "*?assword:*"
send "${password}\r"
expect eof
EOD
Good luck !! Please comment below if you have any new query or need answers for your questions. Let us know how well this helped for your interview :-)
--------------------------------------------------------------------------------
via: http://linoxide.com/linux-shell-script/shell-scripting-interview-questions-answers/
作者:[Petras Liumparas][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://linoxide.com/author/petrasl/

View File

@ -0,0 +1,399 @@
70 个可能的 Shell 脚本面试问题及解答
================================================================================
我们为你的面试准备选择了 70 个可能的 shell 脚面问题及解答。了解脚本或至少知道基础知识对系统管理员来说至关重要,它也有助于你在工作环境中自动完成很多任务。在过去的几年里,我们注意到所有的 linux 工作职位都要求脚本技能。
### 1) 如何向脚本传递参数 ? ###
./script argument
**例子** : 显示文件名称脚本
./show.sh file1.txt
cat show.sh
#!/bin/bash
cat $1
### 2) 如何在脚本中使用参数 ? ###
第一个参数: $1,
第二个参数 : $2
例子 : 脚本会复制文件(arg1) 到目标地址(arg2)
./copy.sh file1.txt /tmp/
cat copy.sh
#!/bin/bash
cp $1 $2
### 3) 如何计算传递进来的参数 ? ###
$#
### 4) 如何在脚本中获取脚本名称 ? ###
$0
### 5) 如何检查之前的命令是否运行成功 ? ###
$?
### 6) 如何获取文件的最后一行 ? ###
tail -1
### 7) 如何获取文件的第一行 ? ###
head -1
### 8) 如何获取一个文件每一行的第三个元素 ? ###
awk '{print $3}'
### 9) 假如第一个等于 FIND如何获取文件中每行的第二个元素 ###
awk '{ if ($1 == "FIND") print $2}'
### 10) 如何调试 bash 脚本 ###
Add -xv to #!/bin/bash
例子
#!/bin/bash xv
### 11) 举例如何写一个函数 ? ###
function example {
echo "Hello world!"
}
### 12) 如何向 string 添加 string ? ###
V1="Hello"
V2="World"
V3=$V1+$V2
echo $V3
Output
Hello+World
### 13) 如何进行两个整数相加 ? ###
V1=1
V2=2
V3=$V1+$V2
echo $V3
Output
3
### 14) 如何检查文件系统中是否存在某个文件 ? ###
if [ -f /var/log/messages ]
then
echo "File exists"
fi
### 15) 写出 shell 脚本中所有循环语法 ? ###
#### for loop : ####
for i in $( ls ); do
echo item: $i
done
#### while loop : ####
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
#### untill oop : ####
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
### 16) 每个脚本开始的 #!/bin/sh 或 #!/bin/bash 表示什么意思 ? ###
这一行说明要使用的 shell。#!/bin/bash 表示脚本使用 /bin/bash。对于 python 脚本,就是 #!/usr/bin/python
### 17) 如何获取文本文件的第 10 行 ? ###
head -10 file|tail -1
### 18) bash 脚本文件的第一个符号是什么 ###
#
### 19) 命令:[ -z "" ] && echo 0 || echo 1 的输出是什么 ###
0
### 20) 命令 “export” 有什么用 ? ###
使变量在子 shell 中公有
### 21) 如何在后台运行脚本 ? ###
在脚本后面添加 “&
### 22) "chmod 500 script" 做什么 ? ###
使脚本所有者拥有可执行权限
### 23) ">" 做什么 ? ###
重定向输出流到文件或另一个流。
### 24) &&& 有什么区别 ###
& - 希望脚本在后台运行的时候使用它
&& - 当第一个脚本成功完成才执行命令/脚本的时候使用它
### 25) 什么时候要在 [ condition ] 之前使用 “if” ? ###
当条件满足时需要运行多条命令的时候。
### 26) 命令: name=John && echo 'My name is $name' 的输出是什么 ###
My name is $name
### 27) bash shell 脚本中哪个符号用于注释 ? ###
#
### 28) 命令: echo ${new:-variable} 的输出是什么 ###
variable
### 29) ' 和 " 引号有什么区别 ? ###
' - 当我们不希望把变量转换为值的时候使用它。
" - 会计算所有变量的值并用值代替。
### 30) 如何在脚本文件中重定向标准输入输出流到 log.txt 文件 ? ###
在脚本文件中添加 "exec >log.txt 2>&1" 命令
### 31) 如何只用 echo 命令获取 string 变量的一部分 ? ###
echo ${variable:x:y}
x - 起始位置
y - 长度
例子:
variable="My name is Petras, and I am developer."
echo ${variable:11:6} # 会显示 Petras
### 32) 如果给定字符串 variable="User:123:321:/home/dir" 如何只用 echo 命令获取 home_dir ? ###
echo ${variable#*:*:*:}
echo ${variable##*:}
### 33) 如何从上面的字符串中获取 “User” ? ###
echo ${variable%:*:*:*}
echo ${variable%%:*}
### 34) 如何使用 awk 列出 UID 小于 100 的用户 ? ###
awk -F: '$3<100' /etc/passwd
### 35) 写程序为用户计算主组数目并显示次数和组名 ###
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
### 36) 如何在 bash shell 中更改标注域分隔符为 ":" ? ###
IFS=":"
### 37) 如何获取变量长度 ? ###
${#variable}
### 38) 如何打印变量的最后 5 个字符 ? ###
echo ${variable: -5}
### 39) ${variable:-10} 和 ${variable: -10} 有什么区别? ###
${variable:-10} - 如果之前没有给 variable 赋值则输出 10
${variable: -10} - 输出 variable 的最后 10 个字符
### 40) 如何只用 echo 命令替换字符串的一部分 ? ###
echo ${variable//pattern/replacement}
### 41) 哪个命令将命令替换为大写 ? ###
tr '[:lower:]' '[:upper:]'
### 42) 如何计算本地用户数目 ? ###
wc -l /etc/passwd|cut -d" " -f1
或者
cat /etc/passwd|wc -l
### 43) 不用 wc 命令如何计算字符串中的单词数目 ? ###
set ${string}
echo $#
### 44) "export $variable" 或 "export variable" 哪个正确 ? ###
export variable
### 45) 如何列出第二个字母是 a 或 b 的文件 ? ###
ls -d ?[ab]*
### 46) 如何将整数 a 加到 b 并赋值给 c ? ###
c=$((a+b))
c=`expr $a + $b`
c=`echo "$a+$b"|bc`
### 47) 如何去除字符串中的所有空格 ? ###
echo $string|tr -d " "
### 48) 重写命令输出变量转换为复数的句子: item="car"; echo "I like $item" ? ###
item="car"; echo "I like ${item}s"
### 49) 写出输出数字 0 到 100 中 3 的倍数(0 3 6 9 …)的命令 ? ###
for i in {0..100..3}; do echo $i; done
for (( i=0; i<=100; i=i+3 )); do echo "Welcome $i times"; done
### 50) 如何打印传递给脚本的所有参数 ? ###
echo $*
echo $@
### 51) [ $a == $b ] 和 [ $a -eq $b ] 有什么区别 ###
[ $a == $b ] - 用于字符串比较
[ $a -eq $b ] - 用于数字比较
### 52) = 和 == 有什么区别 ###
= - 用于为变量复制
== - 用于字符串比较
### 53) 写出测试 $a 是否大于 12 的命令 ? ###
[ $a -gt 12 ]
### 54) 写出测试 $b 是否小于等于 12 的命令 ? ###
[ $b -le 12 ]
### 55) 如何检查字符串是否以字母 "abc" 开头 ? ###
[[ $string == abc* ]]
### 56) [[ $string == abc* ]] 和 [[ $string == "abc*" ]] 有什么区别 ###
[[ $string == abc* ]] - 检查字符串是否以字母 abc 开头
[[ $string == "abc* " ]] - 检查字符串是否完全等于 abc*
### 57) 如何列出以 ab 或 xy 开头的用户名 ? ###
egrep "^ab|^xy" /etc/passwd|cut -d: -f1
### 58) bash 中 $! 表示什么意思 ? ###
后台最近命令的 PID
### 59) $? 表示什么意思 ? ###
前台最近命令的结束状态
### 60) 如何输出当前 shell 的 PID ? ###
echo $$
### 61) 如何获取传递给脚本的参数数目 ? ###
echo $#
### 62) $* 和 $@ 有什么区别 ###
$* - 以一个字符串形式输出所有传递到脚本的参数
$@ - 以 $IFS 为分隔符列出所有传递到脚本中的参数
### 63) 如何在 bash 中定义数组 ? ###
array=("Hi" "my" "name" "is")
### 64) 如何打印数组的第一个元素 ? ###
echo ${array[0]}
### 65) 如何打印数组的所有元素 ? ###
echo ${array[@]}
### 66) 如何输出所有数组索引 ? ###
echo ${!array[@]}
### 67) 如何移除数组中索引为 2 的元素 ? ###
unset array[2]
### 68) 如何在数组中添加 id 为 333 的元素 ? ###
array[333]="New_element"
### 69) shell 脚本如何获取输入的值 ? ###
a) 通过参数
./script param1 param2
b) 通过 read 命令
read -p "Destination backup Server : " desthost
### 70) 在脚本中如何使用 "expect" ? ###
/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect "*?assword:*"
send "${password}\r"
expect eof
EOD
好运 !! 如果你有任何疑问或者问题需要解答都可以在下面的评论框中写下来。让我们知道这对你的面试有所帮助:-)
--------------------------------------------------------------------------------
via: http://linoxide.com/linux-shell-script/shell-scripting-interview-questions-answers/
作者:[Petras Liumparas][a]
译者:[ictlyh](https://github.com/ictlyh)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://linoxide.com/author/petrasl/