Shell程序设计基本语法

使用双引号的字符

双引号是Shell的重要组成部分

$ echo HelloWorld Hello World $ echo “HelloWorld” HelloWorld

如何显示: Hello“World” 以下命令可以吗?$ echo “Hello“World”” 正确方法:echo “Hello \”World\””

条件测试

测试命令 test expression 或 [ expression ] test命令支持的条件测试 字符串比较 算术比较 与文件有关的条件测试 逻辑操作

str1 = “The strings are not equal“ fi mkdir temp 条件语句形式if [ expression ]thenstatementselif [ expression ]thenstatementselif …elsestatementsfi紧凑形式; (同一行上多个命令的分隔符)

case语句 当执行append时,有多少种可能的情况出现?

) cat >> $1 ;; 2) cat >> $2 < $1 ;; *) echo ‘usage: $0 [fromFile] toFile’ ;;esacNo parameter or more than 2Only 1 parameter & the file existOnly 1 parameter & the file not existBoth file nd exist; 1st not existBoth files not existselect语句形式select item in itemlistdostatementsdone作用生成菜单列表举例:一个简单的菜单选择程序#!/bin/shclearselect item in Continue Finishdocase “$item” inContinue) ;;Finish) break ;;*) echo “Wrong choice! Please select again!” ;;esacdoneQuestion: 用while语句模拟?命令组合语句分号串联command1; command2; …条件组合AND命令表格式:statement1 && statement2 && statement3 && …OR命令表格式:statement1 || statement2 || statement3 || …函数调用形式func(){statements}局部变量local关键字函数的调用func para1 para2 …返回值returnyesno(){msg=“$1”def=“$2”” ”echo “$msg”read answerif [ “$answer” ]; thencase “$answer” iny|Y|yes|YES)return 0;;n|N|no|NO)return 1;;*)echo “ ”echo “ERROR: Invalid response, expected \”yes\” or \”no\”.”continue;;}调用函数yesnoif yesno “Continue installation? [n]” 1 ; then:杂项命令

break: 从for/while/until循环退出 continue: 跳到下一个循环继续执行 exit n: 以退出码”n”退出脚本运行 return: 函数返回 export: 将变量导出到shell,使之成为shell环境变量 set: 为shell设置参数变量 unset: 从环境中删除变量或函数 trap: 指定在收到操作系统信号后执行的动作 “:”(冒号命令): 空命令 “.”(句点命令)或source: 在当前shell中执行命令

Shell应用举例

编写一个脚本,,实现对Linux系统中的用户管理,具体功能要求如下 该脚本添加一个新组为class1,然后添加属于这个组的30个用户,用户名的形式为stuxx(其中xx从01到30) 关键命令 groupadd useradd mkdir chown chgrp

#!/bin/sh i=1groupadd class1while [ $i -le 30 ]doif [ $i -le 9 ] ;thenusername=stu0${i}elseusername=stu${i}fiuseradd $username mkdir /home/$usernamechown -r $username /home/$usernamechgrp -r class1 /home/$username i=$(($i+1))done

人只要不失去方向,就不会失去自己

Shell程序设计基本语法

相关文章:

你感兴趣的文章:

标签云: