本文内容来自对 《朱有鹏嵌入式linux核心课程》学习总结
shell 编程学习
1. shell 中调用linux命令
- 直接执行
- 反引号括起来执行。有时候我们在shell中调用linux命令是为了得到这个命令的返回值(结果值),这时候就适合用一对反引号(键盘上
Esc
按键下面的那个按键,和~
在一个按键上)来调用执行命令。
执行结果#!/bin/sh PWD=`pwd` echo "path:" $PWD
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh path: /mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile
2. shell 中的选择分支结构
-
shell 的
if
语句用法很多,在此只介绍常用的。 -
典型
if
语句格式if [表达式]; then xxx yyy zzz else xxx ddd uuu if
-
if
的典型应用-
判断文件是否存在。(-f),注意[]里面前面都有空格,不能省略。
#!/bin/sh if [ -f a.txt ]; then echo "exist" else echo "creat a.txt..." touch a.txt fi
-
判断目录是否存在。(-d)
#!/bin/sh if [ -d "/mnt/hgfs/windwos" ]; then echo "dir exist" else echo "dir no exist" fi
-
判断字符串是否相等。(“str1” = “str2”),注意用一个等号而不是两个。
#!/bin/sh if [ "hello" = "hello" ]; then echo "equal" else echo "not equal" fi
-
判断数字是否相等(-eq),大于(-gt),小于(-lt),大于等于(-ge),小于等于(-le)。
#!/bin/sh if [ 1 -eq 1 ]; then echo "equal" else echo "not equal" fi if [ 2 -gt 1 ]; then echo "greater than" else echo "not greater than" fi if [ 1 -lt 2 ]; then echo "less than" else echo "not less than" fi if [ 5 -ge 5 ]; then echo "greater or equal" else echo "not greater or equal" fi
-
ARM裸机中讲述ARM汇编条件执行时,曾经用过这些条件判断的缩写。(eq就是equal,gt就是greater than,lt就是less than,ge就是greater or equal,le就是less or equal)
-
判断字符串是否为空(-z)注意-z判断时如果变量本身没定义也是不成立(也就是说-z认为没定义不等于为空)
#!/bin/sh str="" if [ -z $str ]; then echo "yes" else echo "no" fi
-
-
if
判断式中使用"-o"
表示逻辑或-
相当于C语言中在
if
后面的条件式中用逻辑与,逻辑或来连接2个式子,最终的if
中是否成立取决于2个式子的逻辑运算结果。#!/bin/sh if [ 1234 -eq 123 -o "hello" = "hello" ]; then echo "yes" else echo "no" fi
-
-
逻辑与
&&
和逻辑或||
与简写的if
表达式相结合-
逻辑
||
#!/bin/sh str="123" [ -z $str ] || echo "not empty"
运行结果
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh not empty
-
逻辑
&&
#!/bin/sh str="" [ -z $str ] && echo "empty"
运行结果
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh empty
-