shell 的使用
用法介绍
第一种
添加权限
chmod +x test.sh
./ tesh.sh
第二种
bash test.sh
第三种
soure test.sh
变量
#!/bin/sh
name="xiaocao"
echo $name
传值
#! /bin/sh
echo "shell 传递参数"
echo "执行文件名: $0"
echo "第一个参数: $1"
chmod +x byCard.sh 12
./ tesh.sh
输出
shell 传递参数
执行文件名: byCard.sh
第一个参数: 12
数组
#! /bin/sh
arry_name=("1" "2" "3")
echo ${arry_name[1]}
echo ${arry_name[@]} #全部
echo ${#arry_name[@]} #长度
执行
bash arry.sh
输出
2
1 2 3
3
算数运算符
原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 expr,expr 最常用。
expr 是一款表达式计算工具,使用它能完成表达式的求值操作。
#! /bin/sh
a=`expr 2 - 3`
echo ${a}
输出
-1
关系运算符
关系运算符只支持数字,不支持字符串,除非字符串的值是数字
代码:
a=10
b=20
if [ $a -eq $b ]
then
echo "相等"
else
echo "不相等"
fi
输出
不相等
布尔运算符
#! /bin/sh
a=10
b=20
if [ $a != $b ]
then
echo "不等"
else
echo "相等"
fi
输出
不等
逻辑运算符
#! /bin/sh
a=10
b=20
if [[ $a -lt 100 && $b -lt 100 ]]
then
echo "ture"
else
echo "false"
fi
输出
ture
字符串运算符
#! /bin/sh
a="abc"
b="efg"
if [ $a = $b ]
then
echo "等于"
else
echo "不等于"
fi
输出
不等于
文件测试运算符
#! /bin/sh
file="/Users/apple/Documents/Shell/for.sh"
if [ -r $file ]
then
echo "可读"
else
echo "不可读"
fi
输出
可读
echo命令
#! /bin/sh
echo ti tis a test
#转义
echo \"It is a test\"
#显示变量
read name
echo "$name ti tis atesr"
echo "OK! \n"
echo "It is a test"
echo "OK! \c"
echo "Tt is a test"
#echo "ti is a test " >outFile
echo `date`
输出
ti tis a test
"It is a test"
xiaocao
xiaocao ti tis atesr
OK!
It is a test
OK! Tt is a test
2019年12月 4日 星期三 20时49分12秒 CST
printf命令
#! /bin/sh
echo "Hello ,Shell"
printf "Hello,Shell \n"
printf "%-10s %-8s %-4s \n" 姓名 性别 体重kg
printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234
printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543
printf "%d %s\n" 1 "abc"
printf "%s\n" avc
printf "%s %s %s\n" a b c d e f g h i j
输出:
Hello ,Shell
Hello,Shell
姓名 性别 体重kg
郭靖 男 66.12
杨过 男 48.65
1 abc
avc
a b c
d e f
g h i
j
test 命令
#! /bin/sh
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo "相等"
else
echo "不相等"
fi
num1="11"
num2="1123"
if test $num1 = $num2
then
echo '两个字符串相等!'
else
echo '两个字符串不相等!'
fi
cd /bin
if test -e ./bash
then
echo "文件存在"
else
echo "文件不存在"
fi
输出:
相等
两个字符串不相等!
文件存在