shell学习
对于从事软件工作的兄弟,linux下会写shell脚本是非常重要
#!/bin/sh 定义使用/bin/sh来解释执行,#!是特殊的表示符,/bin/sh是此解释此脚本路径
还有#!/bin/bash
hell 中的全局变量有以下几个:
$#: 执行 shell 脚本时的命令行参数,不包括脚本本身
$?: 执行上一条 shell 命令的返回值
$0: shell 脚本程序自身的名称
用户自定义变量规则:
首个字符必须是(a~z,A~Z),可下划线(——)不能空格,不能使用符号标点,不能使用 shell 里的关键字
test命令:测试条件表达式(字符串测试、整数测试、逻辑测试、文件测试)
字符串测试:
test –n string #字符串的长度非零
test –z string #字符串的长度是否为零
test string1=string2 #字符串是否相等,若相等返回true
test string1!=string2 #字符串是否不等,若不等反悔false
整数测试:
test int1 -eq int2 #判断两个数是否相等
test int1 -ne int2 #判断两个数是否不相等
test int1 -gt int2 #判断整数 1 是否大于整数 2
test int1 -ge int2 #判断整数 1 是否大于等于整数 2
test int1 -lt int2 #判断整数 1 是否小于整数 2
test int1 -le int2 #判断整数 1 是否小于等于整数 2
逻辑测试
if test #表达式为真
if test ! #表达式为假
test 表达式1 –a 表达式2 #两个表达式都为真
test 表达式1 –o 表达式2 #两个表达式有一个为真
test 表达式1 ! 表达式2 #条件求反
二:shell脚本的条件判断-命令成功或失败,条件表达式为真还是假;
if 表达式:
if 表达式
then
fi
if 表达式1
then
else
fi
if 表达式1
then
cmd1
elif
cmd2
...
else
cmd4
fi
case string in
strl)
命令串1;;执行
str2)
命令串2;;执行
esac(case的反着写)
for var
do
cmd
done
for i in var
do
cmd
done
while 条件表达式
do
命令
done
shell脚本中重复功能用函数封装
function 函数名
{
...
}
shell中
echo #显示文字
exit #推出shell脚本或当前进程
sleep #暂停
expr #命令可以实现数值运算、数值或字符串比较、字符串匹配、字符串提取、字符串长度计算等功能
break #强制推出当前循环
continue #推出本次循环
对于从事软件工作的兄弟,linux下会写shell脚本是非常重要
#!/bin/sh 定义使用/bin/sh来解释执行,#!是特殊的表示符,/bin/sh是此解释此脚本路径
还有#!/bin/bash
hell 中的全局变量有以下几个:
$#: 执行 shell 脚本时的命令行参数,不包括脚本本身
$?: 执行上一条 shell 命令的返回值
$0: shell 脚本程序自身的名称
用户自定义变量规则:
首个字符必须是(a~z,A~Z),可下划线(——)不能空格,不能使用符号标点,不能使用 shell 里的关键字
test命令:测试条件表达式(字符串测试、整数测试、逻辑测试、文件测试)
字符串测试:
test –n string #字符串的长度非零
test –z string #字符串的长度是否为零
test string1=string2 #字符串是否相等,若相等返回true
test string1!=string2 #字符串是否不等,若不等反悔false
整数测试:
test int1 -eq int2 #判断两个数是否相等
test int1 -ne int2 #判断两个数是否不相等
test int1 -gt int2 #判断整数 1 是否大于整数 2
test int1 -ge int2 #判断整数 1 是否大于等于整数 2
test int1 -lt int2 #判断整数 1 是否小于整数 2
test int1 -le int2 #判断整数 1 是否小于等于整数 2
逻辑测试
if test #表达式为真
if test ! #表达式为假
test 表达式1 –a 表达式2 #两个表达式都为真
test 表达式1 –o 表达式2 #两个表达式有一个为真
test 表达式1 ! 表达式2 #条件求反
二:shell脚本的条件判断-命令成功或失败,条件表达式为真还是假;
if 表达式:
if 表达式
then
fi
if 表达式1
then
else
fi
if 表达式1
then
cmd1
elif
cmd2
...
else
cmd4
fi
case string in
strl)
命令串1;;执行
str2)
命令串2;;执行
esac(case的反着写)
for var
do
cmd
done
for i in var
do
cmd
done
while 条件表达式
do
命令
done
shell脚本中重复功能用函数封装
function 函数名
{
...
}
shell中
echo #显示文字
exit #推出shell脚本或当前进程
sleep #暂停
expr #命令可以实现数值运算、数值或字符串比较、字符串匹配、字符串提取、字符串长度计算等功能
break #强制推出当前循环
continue #推出本次循环