# shell **Repository Path**: SeeDeer/shell ## Basic Information - **Project Name**: shell - **Description**: 学会shell脚本编程会极大的提高你的工作效率~ - **Primary Language**: Shell - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-03-31 - **Last Updated**: 2021-02-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # shell * ubuntu下tftp服务器安装配置脚本 tftp.sh * ubuntu下samba服务器安装配置脚本 samba.sh ## sed流编辑器使用 格式: sed option pattern file_name 1. 修改文件中某一行的内容 * 定位行的方法: 1. 数字直接定位行数; 2. /patten/ 模式匹配 * sed -n '/^ssid=/c\ssid=\"OpenWrt-45\"/p' /etc/wpa_supplican 2. 常用选项说明 * -i[SUFFIX], 直接修改文件不输出到STDOUT \ -i.bak修改前先备份文件file_name.bak * -e , 顺序执行多条sed命令 * -n , 常和p命令配合使用,打印出匹配模式的文本到STDOUT * -F , 顺序加载脚本文件中的命令执行 ```shell echo "/^TFTP_DIRECTORY=/c\TFTP_DIRECTORY=\"${directory}\""> script.sed echo "/^TFTP_ADDRESS=/c\TFTP_ADDRESS=\"0.0.0.0:69\"" >> script.sed echo "/^TFTP_OPTIONS=/c\TFTP_OPTIONS=\"-l -c -s\"" >> script.sed # cat script.sed exec_cmd sudo sed -i -f script.sed $conf_file ``` ## shell函数使用 1. 定义方法: ```shell func_name() { # 函数可定义在脚本的任意位置,无需在文件头部声明,便可找到 # 函数体内使用的变量请用关键字local声明为局部变量,防止和外面的全局变量冲突 # 函数参数传入方法和脚本的参数一致: $0=函数名称 \ $1~$n=函数第1~n个参数 # \ $*参数列表(作为一个字符串) \ $@参数列表(作为多个字符串) # \ $# 参数列表个数 # 返回码: return 0 \ 不显式调用时返回最后一条的命令退出码 # 调用方法: func_name param1 param2 ... paramN } function func_name { # 第二种定义方法 } ``` ## 脚本执行过程中提示用户输入数据 read 命令: -p , 添加提示打印 ```shell while true do read -p "please input a file sharing directory:" directory if [ -n $directory ];then sudo mkdir $directory break else continue fi done ``` ## shell条件判断 1. 数值比较 用法 | 说明 --- | --- [ \$a -eq \$b ] | 变量a == 变量b [ \$a -ne \$b ] | 变量a != 变量b [ \$a -ge \$b ] | 变量a >= 变量b [ \$a -gt \$b ] | 变量a > 变量b [ \$a -le \$b ] | 变量a <= 变量b [ \$a -lt \$b ] | 变量a < 变量b 2. 字符串比较 用法 | 说明 --- | --- [ str1 = str2 ] | 是否相同? [ str1 != str2 ] | 是否不同? [ -n str ] | 长度是否非零? [ -e str ] | 长度是否为零? [ str1 < str2 ] | 是否小于? [ str1 > str2 ] | 是否大于? 3. 文件比较 vgeh | 输出 --- | --- [ -e file ] | 检查file是否存在 [ -d file ] | 检查file是否存在,并且是一个目录 [ -f file ] | 检查file是否存在,并且是一个文件 [ -s file ] | 检查file是否存在,并且非空 [ -r file ] | 检查file是否存在,并且可读 [ -w file ] | 检查file是否存在,并且可写 [ -x file ] | 检查file是否存在,并且可执行 [ -O file ] | 检查file是否存在,并且属于当前用户所有 [ -G file ] | 检查file是否存在,并且所属用户组和当前用户相同 [ file1 -nt file2 ] | 检查file1是否比file2新(根据最后修改时间) [ file1 -ot file2 ] | 检查file1是否比file2旧(根据最后修改时间) ## 将命令输出赋值给变量 用中括号()或者反引号`` IS_TFTP=$(which tftp) ## 数值运算 整数运算:expr命令,bash shell扩展了一种方法用于计算 $[计算式] 实现变量自增 var=$[$var + 2]