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