c语言shell脚本,ubuntu shell脚本与C语言

写这个题目时,不是要列举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上运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值