#!/bin/bash
#---------- 一些命令 ---------#
:<<eof
chmod +x ./test.sh #更改执行权限
expr 表达式 #求表达式的值
eof
:<<!
这也可用于多行注释
!
#---------- 打印 -----------#
echo -e "hello world \nhello shell" # 打印;-e开启转义
echo `date`
printf "%-10s %-8s %-4.2f\n" 你好 吗 11.123456
#--------- 变量 ----------#
h0=helloshell # 变量;等号两边不能有空格
h='hello shell' # 字符有空格时,需要用引号
readonly h # 只读
unset h0 # 删除变量,不能删只读变量
echo ${h} # 使用变量
# 字符串
str='this is a string' # 单引号里的任何字符都会保持原样,转义或取变量都无用
newstr="I know that \"$str\",\n" # 可用转义字符,可用$取变量
echo ${newstr:0:5} # 切片
echo ${#newstr} # 获取字符串长度
echo `expr length "${newstr}"` # 等价上面
echo `expr index "$newstr" ir` # 查找第一个i或r出现的位置
# 数组
array=(1 2 3 4 5 6)
echo $array # 输出为第一个值
array[0]=0
echo ${array[0]} # 输出索引为0的值;要加{}
echo ${array[@]} # 输出全部
echo ${array[*]} # 同上
echo ${#array[*]} # 获取长度
# 参数(类似于c++中的argv) ./demo.sh 1 2
echo "first:$0" # 文件名
echo "second:$1" # 第一个参数
third=$2 # 第二个
echo third:$third
echo $# # 传递到脚本的参数个数
echo $* # 显示所有参数
echo $$ # 显示当前进程号
echo $! # 显示后台运行的最后一个进程号
echo $@ # 同*
echo $- # 同set
echo $? # 显示命令的退出状态:0-->没有错误
# 基本运算符
#算数运算符
a=2 # 运算符左右要留空格
b=5 # ``不是单引号
echo `expr $a + $b` # 加
echo `expr $a - $b` # 减
echo `expr $a \* $b` # 乘
echo `expr $a / $b` # 除
echo `expr $a % $b` # 取余
a=$b # 赋值
echo ${a,b}
[ $a == $b ] # 等于;注意空格
[ $a != $b ] # 不等于;注意空格
#关系运算符
[ $a -eq $b ] # 相等
[ $a -ne $b ] # 不等
[ $a -gt $b ] # 大于
[ $a -lt $b ] # 小于
[ $a -ge $b ] # 大于等于
[ $a -le $b ] # 小于等于
# 逻辑运算符
[[ $a -lt 10 && $a -lt 10]] # 与
[[ $a -lt 10 || $a -lt 10]] # 或
# 字符串运算符
str1='hello'
str2='world'
[ -z $str1 ] # 长度是否为0
[ -n $str1 ] # 长度是否不为0
[ $str1 ] # 是否为空
# 文件测试运算符
#-------- 流程控制 --------#
# if else
if condition1
then
command1
command2
elif conditon2
then
command3
else
command4
fi
$ if [ conditon1 ]; then command1; elif [ condition2 ];then command3; else command4; fi
# for
for i in item1 item2 item3 ... itemN
do
command1
command2
command3
done
$ for i in item1 item2 ... itemN; do command1; command2;...;done
# while
while condition1
do
command
done
# until
until condition
do
command
done
# case
case 值 in
case1) command1 command2
;;
case2) command1 command2
;;
esac
# break continue
# 函数
fuction_name()
{
action;
[ return int;]
}
#---------- 重定向 -----------#
command > file
command < file
command >> file # 追加模式
n >& m # 合并
n <$ m
0:STDIN 1:STDOUT 2:STDERR
shell编程基础之小结
最新推荐文章于 2022-04-30 09:29:12 发布