shell编程:定义简单标准命令集

时间:2021-06-19 09:48:56

shell是用户操作接口的意思,操作系统运行起来后都会给用户提供一个操作界面,这个界面就叫shell,用户可以通过shell来调用操作系统内部的复杂实现,而shell编程就是在shell层次上进行编程,如Linux中的脚本编程。

shenll运行原理:由消息接收、解析、执行构成的死循环。

命令行shell:该死循环包含3个模块(命令接收、命令解析、命令执行),命令行有一个标准命令集,用户输入的命令若不是标准命令,则提示用户这不是一个合法命令行,然后重新回到命令行让用户输入下一个命令。

常见的shell:uboot、Linux终端、Windows图形界面等

shell实例1:使用printf和scanf做输入回显

#include <stdio.h>
#include <string.h> #define MAX_LINE_LENGTH 256 // 定义命令行长度,命令不能超过这个长度 int main(void)
{
char str[MAX_LINE_LENGTH]; // 用来存放用户输入的命令内容 while ()
{
// 打印命令行提示符,注意不能加换行
printf("Please input your command:#");
// 清除str数组以存放新的字符串
memset(str, , sizeof(str));
// shell第一步:获取用户输入的命令
scanf("%s", str);
// shell第二步:解析用户输入命令 // shell第三步:处理用户输入命令
printf("%s\n", str);
} return ;
}

memset(str,0,sizeof(str))

 //清除数组
void memset(char *p, int val, int length)
{
int i; for (i=; i<length; i++)
{
p[i] = val;
}
}

shell实例2:解析用户输入命令并回显

 #include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 256 // 命令行长度,命令不能超过这个长度 // 宏定义一些标准命令
#define led "led"
#define lcd "lcd"
#define pwm "pwm"
#define CMD_NUM 3 // 当前系统定义的命令数 char g_cmdset[CMD_NUM][MAX_LINE_LENGTH]; // 初始化命令列表
static void init_cmd_set(void)
{
memset(g_cmdset, , sizeof(g_cmdset)); // 先全部清零
strcpy(g_cmdset[], led);
strcpy(g_cmdset[], lcd);
strcpy(g_cmdset[], pwm);
} int main(void)
{
int i = ;
char str[MAX_LINE_LENGTH]; // 用来存放用户输入的命令内容 init_cmd_set(); while ()
{
// 打印命令行提示符,注意不能加换行
printf("Please input your command:#");
// 清除str数组以存放新的字符串
memset(str, , sizeof(str));
// shell第一步:获取用户输入的命令
scanf("%s", str);
// shell第二步、第三步:解析用户输入命令、处理用户输入命令
for (i=; i<CMD_NUM; i++)
{
if (!strcmp(str, g_cmdset[i]))
{
// 相等,找到了这个命令,执行这个命令所对应的动作。
printf("您输入的命令是:%s,是合法的\n", str);
break;
}
}
if (i >= CMD_NUM)
{
// 找遍了输入命令都没找到这个符合要求的,则输出相应指示
printf("%s不是一个内部合法命令,请重新输入\n", str);
}
} return ;
}

void strcpy(char *dst, const char *src)

 //复制字符串常量到数组中
void strcpy(char *dst, const char *src)
{
while (*src != '\0')
{
*dst++ = *src++;
}
}

int strcmp(const char *cs, const char *ct)

 //比较两字符串是否相同
int strcmp(const char *cs, const char *ct)
{
unsigned char c1, c2; while () {
c1 = *cs++;
c2 = *ct++;
if (c1 != c2)
return c1 < c2 ? - : ;
if (!c1)
break;
}
return ;
}

 shell实例3:shell编程将用户输入的字符串命令按照空格分隔成多个字符串,依次放入cmd二维数组中并解析执行命令

 void cmdsplit(char cmd[][MAX_LEN_PART], const char *str)
{
int m = , n = ;
while (*str != '\0')
{
if (*str != ' ')
{
cmd[m][n] = *str;
n++;
}
else
{
cmd[m][n] = '\0';
n = ;
m++;
}
str++;
}
cmd[m][n] = '\0';
}

解析命令:

 void cmd_parser(char *str)
{
int i; // 第一步,先将用户输入的次命令字符串分割放入cmd中
cmdsplit(cmd, str); // 第二步,将cmd中的次命令第一个字符串和cmdset对比
cmd_index = -;
for (i=; i<CMD_NUM; i++)
{
// cmd[0]就是次命令中的第一个字符串,也就是主命令
if (!strcmp(cmd[], g_cmdset[i]))
{
// 相等,找到了这个命令,就去执行这个命令所对应的动作。
cmd_index = i; break;
}
}

执行命令

 void cmd_exec(void)
{
switch (cmd_index)
{
case :
do_cmd_led(); break;
case :
case :
default:
do_cmd_notfound(); break;
}
}