shell脚本常用一些指令

最近发现曾经使用的很多东西现在看到都没有什么印象了,还需要上网重新查找,非常不方

便,所以打算将以前记录的东西写下来,保存,便于后续查看。

以下是我以前编写shell脚本时记录的笔记

$? --标识返回上一个命令的结果值(两种可能:0:执行成功,非零:执行未成功)

$0  --代表执行的文件名称,从1开始代表执行文件所需要的参数(例如: ls -l /etc)

$* --这个程序的所有参数

$# --这个程序的参数个数

$$ --这个程序的PID

$!  --执行上一个后台命令的PID


shell命令

read USERNAME(变量名)  --从键盘上读取数据,赋给变量

sh -x(指令) 脚本名称   --调试脚本

sh -n(指令) 脚本名称   --不执行脚本只是检查语法的模式,将返回所有语法错误

expr --对整数型变量进行算术运算(注: *(乘号)需要转译 \*)


if 判断语句

test str1==str2  --测试字符串是否相等

test str1!=str2  --测试字符串是否不相等

test str1        --测试字符串是否不为空

test -n str1     --测试字符串是否不为空

test -z str2     --测试字符串是否为空

test -int1 -eq int2  --判断整数是否相等(int1==int2)

test -int1 -ge int2  --判断整数是否相等(int1>=int2)

test -int1 -gt int2  --判断整数是否大于(int1>int2)

test -int1 -le int2  --判断整数是否小于等于(int1<=int2)  

test -int1 -lt int2  --判断整数是否小于(int1<int2)

test -int1 -ne int2  --判断整数是否不相等(int1!=int2)

test -d file  --指定文件是否是目录

test -f file  --指定文件是否是常规文件

test -x file  --指定文件是否是可执行

test -r file  --指定文件是否是可读

test -w file  --指定文件是否是可写

test -a file  --指定文件是否存在

test -s file  --文件的大小是否非0


test -d $1 等价于 [-d $1]

多个添加的联合

-a:逻辑与,仅当两个条件都成立时,结果为真

-o: 逻辑或,两个条件只要有一个成立,结果为真

exit 0 --表示正常退出(非0表示非正常退出)

循环语句
for ...done语句

for 变量 in 名字表
 
   do
      命令列表

   done

awk -F : 分割符(以:作为分割符) 例如: awk -F: '$3==0 {print $1}' /etc/passwd (/etc/passwd格式为:root:x:0:0:root:/root:/bin/bash)


阻止交互方式

例如: echo 123456 | passwd --stdin shedon(用户名)

直接将打印出来的123456赋值给 passwd

until 条件
  do
   命令
  done

条件为假的时候执行循环


shift  --将参数向左移一位, 移走的参数不可用

例如: sh shift.sh  aa bb cc dd ee

       使用shift 参数会变为 bb cc dd ee

猜你喜欢

转载自liujun58love.iteye.com/blog/1534831