- 什么是shell编程?
允许执行程序,输入并获取某种半结构化的输出,电脑的终端就是一个shell - shell 基于空格分割命令并进行解析,然后执行第一个单词代表的程序,并将后续的单词作为程序可以访问的参数。如果希望传递的参数中包含空格(例如一个名为 My Photos 的文件夹),要么用使用单引号,双引号将其包裹起来,要么使用转义符号 \ 进行处理(My\ Photos)。
- 可以在程序中创立连接,可以将输入输出流分别重定向到文件中
missing:~$ echo hello > hello.txt
missing:~$ cat hello.txt
hello
missing:~$ cat < hello.txt
hello
missing:~$ cat < hello.txt > hello2.txt
missing:~$ cat hello2.txt
hello
可以使用>>向文件中追加内容
missing:~$ echo world >> hello.txt
missing:~$ cat hello.txt
hello
world
- shell定义变量的方式:定义变量时不能用空格,使用变量时要在变量前加$符号,使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。使用 unset 命令可以删除变量。语法:
unset variable
,unset命令不能删除只读变量。 - 双引号里面可以有变量,也可以出现转义字符,但是单引号里面不可以
- 拼接字符串使用
echo $str1 $str2
即可 - 获取字符串长度:
echo ${#str}
- 字符串切片: `echo ${str:1:4}
* and @
都有表示全部的意思- 表达式,要使用
expr 2 + 2
这个表达式要用反引号括起来,而且数字和操作符之间一定要有空格,另外乘法*
号 要打\
转义符号 - 执行需要传入参数的.sh文件,使用
./pra.sh 1 2 3
执行 - 逻辑运算符
&&
AND, ||
OR - 流程控制方法为
if then (else) fi
或者if then elif then else fi
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
for do done
while condition
do
command
done
while do done
- 查找某个文件中包含:
grep string file
, 反向搜索,查看某个文件中不包含某个字符串的内容有那些grep -v string file