Linux环境下的C语言和shell编程

Linux环境下编程笔记

1.shell脚本的hello wored

新建一个shell脚本touch hello.sh
在这里插入图片描述
在这里插入图片描述
通过shell指令执行脚本:
使用chomd 775开放权限或者使用bash直接运行
在这里插入图片描述
在这里插入图片描述

#!/bin/bash
echo "hello world my shell"

2.C语言脚本的hello wored

1.新建一个c文件touch hello.c
2.编译:gcc hello.c回车,然后会生成一个名叫a.out 的执行文件
生成指定名字的.out文件gcc hello.c -o hello.out
3.运行:./a.out回车
在这里插入图片描述
在这里插入图片描述

#include<stdio.h>
#include<unistd.h>//延时函数引用头文件
int main(void)
{
  printf("hello word\n");
  sleep(3);//延时函数秒单位
   printf("hello word\n");
  return 0;
}

C语言带有输入参数

#include<stdio.h>
int main(int argc, char* argv[])
{
        int i;
        printf("一共传入了 %d 个参数\n", argc);
        for (i = 0; i < argc; i++) {
                printf("argv[%d] = %s\n", i, argv[i]);
        }

        if (strcmp(argv[1], "funA") == 0) {
                printf("执行功能A!\n");
        } else {
                printf("执行功能B!\n");
        }

  return 0;
}

在这里插入图片描述
argv[0]存储的,是程序运行的全路径名。argv[1]、argv[2]…argv[argc - 1]存储的,是我们在调用二进制后面所加上的一些字符串参数

#include <stdio.h>
#include <string.h> 
int main(int argc, char* argv[]) {		
	
	if (argc < 2) {
		printf("请输入参数!\n");
		return 1;
	} 
	
	int i, maxi = atoi(argv[1]);
	for (i = 1; i <= maxi; i++) {
		printf("%d\n", i);
	} 
	
	return 0;
} 

在这里插入图片描述

3.C语言调用shell命令及脚本

Linux中C语言执行shell脚本的方法: https://blog.csdn.net/u010299133/article/details/85637263
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>//system函数驱动shell命令
#include<unistd.h>//延时函数引用头文件
int main(void)
{
  printf("hello word\n");
  sleep(3);//延时函数秒单位
   printf("hello word\n");
  system("bash ./hello2.sh");//执行shell脚本
  return 0;
}

4.shell脚本的获取权限登录

sudo apt-get install tcl
sudo apt-get install expect

更新命令:
sudo apt-get update  #更新
sudo apt-get upgrade  #升级,需要用update更新完才能upgrade

应用示例

#!/usr/bin/expect

set timeout 1

spawn sudo ./TN.sh
expect " 密码"     #这个空格啊,相当重要

send "123456a@\n"  

expect eof
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值