这边提到的5个面试问题,延续之前的有关Linux面试问题和答案。如果你是Tecmint的读者,你的支持我非常感谢。
1. 写一个shell脚本来得到当前的日期,时间,用户名和当前工作目录。
答案 : 输出用户名,当前日期和时间,以及当前工作目录的命令就是logname,date,who i am和pwd。
现在,创建一个名为userstats.sh文件,将下面的代码添加到它。
代码如下:
#!/bin/bash
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current directory `pwd`"
给它添加执行权限,并且执行他。
代码如下:
# chmod 755 userstats.sh
# ./userstats.sh
样例输出
代码如下:Hello, avi
Current date is Sat Jun 7 13:05:29 IST 2014
User is avi pts/0 2014-06-07 11:59 (:0)
Current directory /home/avi/Desktop
2.写一个shell脚本,进行两个数字的相加,如果没有输入参数就输出错误信息和一行使用说明
答案 : 下面是简单的shell脚本以及描述,如果没有命令行参数,它会抛出错误与如何使用脚本的说明。
再创建一个名为twonumbers.sh文件和下面的内容添加到文件里。
代码如下:
#!/bin/bash
# The Shebang
if [ $# -ne 2 ]
# If two Inputs are not received from Standard Input
then
# then execute the below statements
echo "Usage - $0 x y"
# print on standard output, how-to use the script (Usage - ./1.sh x y )
echo " Where x and y are two nos for which I will print sum"
# print on standard output, “Where x and y are two nos for which I will print sum ”
exit 1
# Leave shell in Error Stage and before the task was successfully carried out.
fi
# End of the if Statement.
echo "Sum of $1 and $2 is `expr $1 + $2`"
# If the above condition was false and user Entered two numbers as a command Line Argument,
it will show the sum of the entered numbers.
给他添加可执行权限,并且执行。
代码如下:# chmod 755 two-numbers.sh
情形一: 未输入两个数字作为命令行参数运行脚本,你将得到下面的输出。
样例输出
代码如下:# ./two-numbers.sh
Usage - ./two-numbers.sh x y
Where x and y are two nos for which I will print sum
情形二: 当数字存在时,你会得到如图所示的结果。
新闻热点
疑难解答