**基本指令的基础:
判断语句if的使用:
#!/bin/bash
if[condition]
then
command1
elif condition2
then
command3
fi
condition:
- 数值比较:
命令 | 意义 |
---|---|
-eq | 相等 |
-ge | 大于等于 |
-gt | 大于 |
-le | 小于等于 |
-lt | 小于 |
-ne | 不等于 |
- 字符串比较(!!因为><和重定向符号相同用\隔开):
命令 | 意义 |
---|---|
str1 = str2 | 相等 |
!= | 判断字符串是否相同 |
< | 小于 |
> | 大于 |
-n str1 | 长度是否非0 |
-z str1 | 长度是否为0 |
- 文件比较:
命令 | 意义 |
---|---|
-d file | 是否存在并且是一个目录 |
-e | 是否存在 |
-f | 是否存在并且是一个文件 |
-s | 是否存在并且非空 |
more | … |
for循环的使用(expC语言风格)
for var in list
do
commands
done
- 读取list中的值比如:(请注意转义字符和单引号的使用)
for test in i don\'t konw "this'll" work
do
echo the next is $test
done
#或者将list赋值给变量
#---------
list = i don\'t konw "this'll" work
for test in list
#---------
$
the next is if
the next is i
the next is don't
the next is know
the next is this'll
the next is work
$
- 从命令读取值
#reading values from a file
#IFS= $'\n';将会忽略空格和制表符
file = "test"
for test in `cat $file`;do
echo "$test"
done
- 遍历文件夹和文件
for file in /home/lucy/test/*
do
if [ -d "$file" ]
then
echo "$file" is a direct
elif [ -f "$file" ]
then
echo" $file is a file"
fi
done
while循环的使用
while [condition]
do
command
done
#condition和if中的判断条件相似