写这个题目时,不是要列举shell功能如何强大,本文的初衷是通过一个简单的 bash
shell程序和对应的C程序来浅析shell脚本语言的魅力。
下面仅用密码验证程序来浅析shell:
所谓密码验证程序,即让用户输入密码,通过密码文件验证输入的密码。如果连续三次输入错误,则退出程序;否则密码正确。
C语言实现
#include
#include
#include
int main()
{
int count = 1; // 输入密码的次数
char password[10]; // 存储输入的密码
printf("Enter your
password:\n");
scanf("%s", password);
while (strcmp(password,
"young") != 0 && count != 3) // 验证输入的密码,输入错误时,重新输入。
{
printf("Try it
again!\n");
printf("Enter your
password:\n");
scanf("%s", password);
count++;
}
if (strcmp(password, "young")
!= 0) // 三次输入错误,退出程序。
{
return 1;
}
else
{
printf("you can login
successfully!\n"); // 密码正确
}
return 0;
}
shell 实现
#!/bin/sh
#
# this is a shell script of passwd.sh
# written by young on Sep 23th, 2009
#
count=1 # 输入密码的次数
echo "Enter your pass word:"
read word # 输入密码
while [ "$word" != "young" -a
"$count" -ne 3 ] # 验证输入的密码,输入错误时,重新输入。
do
echo "Try it again!"
count=`expr $count + 1`
echo "Enter your pass word:"
read word
done
if [ "$word" != "young" ] #
三次输入错误,退出脚本
then
exit 1
else
echo "you can login successfully!" # 密码正确
fi
在终端上输入以下命令:
chmod a+x
passwd.sh (all+exectable )
其作用是,给脚本文件passwd.sh赋予可执行权限。这样可以直接在终端上输入passwd.sh来运行脚本。此外,也可以采用sh
passwd.sh命令来运行脚本文件。
由于shell是脚本语言,不需要编译,只需使用shell脚本解释器逐行解释,因而运行速度比C程序快。此外shell中的变量不需要声明,就能使用;而C语言中,变量必须声明后,才能使用。shell脚本的简洁,这点不用我多说,通过上面的例子大家也能看得出来。
说明:
以上程序均能在Ubuntu9.04、Redhat
等Linux版本和SGI Unix上运行。