关于bash
bash的内部命令:shell在启动时就调入内存。
bash的外部命令:使用时才从硬盘中读入内存。
命令通配符:
? : 匹配任意一个字符
[] : 匹配括号中的任意单字符
* : 匹配任何的字符或者字符串,包括空字符串
shell程序
shell程序本质是普通文本文件,加上可执行权限后可以让shell执行文本中的程序。
#! shell compiler
# filename
shell statements
t.sh:
#!/bin/bash
#t.sh
echo "hello Linux, "
echo "I love you"
$ chmod +x t.sh
$ ./t.sh
hello Linux,
I love you
shell语言是一种解释型语言,
shell变量有:局部变量、环境变量、位置变量。
shell变量没有数据类型,变量赋值之后只需要加上$即可使用,不带空格的字符串可以不加引号。
环境变量的定义:export var=value
输出:echo $var (重启失效)
在/etc/profile中可以定义环境变量
位置变量:在shell程序运行时传入的参数
$n
n:1–9
$ cat dex.sh
#!/bin/bash
#location var
echo $1
echo $2
$ ./dex.sh hello world
hello
world
shell算术运算符中的**
代表两个变量的幂运算。
$ cat cal.sh
#/bin/bash
#calculate
a=12
echo $[$a**$1]
b=$[$a*$1]
echo $b
$ ./cal.sh 2
144
24
echo中的输出字符
\c:末尾加上\c表示这一行输出完毕以后不换行
read命令可以读取标准输入到一个变量。
$ read var
this is a read test
$ echo $var
this is a read test
$ read var1 var2 var3
this is a happy day
$ echo $var1
this
$ echo $var2
is
$ echo $var3
a happy day
commond 1 > filename 标准输出重定向到文件中
commond 2 > filename 标准输出的错误重定向到文件中
commond > filename 2>&1 标准输出和标准错误重定向到文件中
$ ls > doc2 2>&1
command < filename1 > filename2 将file1作为标准输入,file2作为标准输出
双引号和单引号的区别:
$ echo "$var1"
this
$ echo '$var1'
$var1
$ echo "hello \"linux\""
hello "linux"
$ echo 'hello \"linux\"'
hello \"linux\"
test测试命令
- 文件状态测试:指的是对文件的权限、有无、属性、类型等内容进行判断
- 数值比较
symbol | effect |
---|---|
eq | equal 相等 |
ne | not eqaul 不等 |
le | less or equal 小于等于 |
ge | greater or equal 大于等于 |
gt | greater than 大于 |
lt | less than 小于 |
* 逻辑测试
symbol | effect |
---|---|
a | and 逻辑与 |
o | or 逻辑或 |
! | 非 逻辑否 |
* 字符串比较
symbol | effect |
---|---|
= | 相等 |
!= | 不等 |
-z | 空串 |
-n | 非空 |
流程控制
if 语句
格式:
if condition1
then command1
fi
if condition1
then command1
elif condition2
then command2
else command3
fi
for循环
格式:
for var in list
do
command1
command2
done
until循环——直到条件成真的时候才停下来。
格式:
until condition
do
commond1
done
while循环
while condition
do
command
done
练习
- 写一个判断文件读,写,可执行的权限shell脚本
#!/bin/bash
#rxw
if test -r $1
then echo this file can be read.
else echo this file can not be read.
fi
if test -w $1
then echo can be wrote.
else echo can not be wrote.
fi
if test -x $1
then echo can be executed.
else echo can not be executed.
fi
- 打印当前目录下所有的shell脚本文件
#!/bin/bash
#ls sh file
files=`ls *.sh`
for file in $files
do
echo $file
done
- 每0.5秒执行一次ls命令
$ cat ls.sh
#!/bin/bash
#ls for 0.5s
for i in {1..10}
do
ls
usleep 500000 #or : sleep 0.5
done