[root@localhost script]# ./test.sh henry 666
===$n===
./test.sh
henry
666
===$#===
2
$*、$@
$*: 把所有的参数看成一个整体
$@: 将所有的参数看成一个列表, 后续可用于遍历
[root@localhost script]# cat test.sh
#!/bin/bash
echo '===$n==='
echo $0
echo $1
echo $2
echo '===$#==='
echo $#
echo '===$*==='
echo $*
echo '===$@==='
echo $@
[root@localhost script]# ./test.sh a b c d e
===$n===
./test.sh
a
b
===$#===
5
===$*===
a b c d e
===$@===
a b c d e
if [ 条件判断 ]
then
程序
elif [ 条件判断 ]
then
程序
else
程序
fi
使用实例
输入一个数字, 如果数字是1则输出"This is 1", 否则输出"This not 1"
[root@localhost script]# cat ./script.sh
#!/bin/bash
if [ $1 = 1 ]
then
echo "This is 1"
else
echo "This not 1"
fi
[root@localhost script]# ./script.sh 1
This is 1
输入一个字符串, 若此字符串是"henry"则输出"This is henry", 否则输出"This not henry"
[root@localhost script]# cat script.sh
#!/bin/bash
if [ "$1"x = "henry"x ]
then
echo "This is henry"
else
echo "This not henry"
fi
[root@localhost script]# ./script.sh henry
This is henry
在$1后面拼接字符串'x'的目的是, 当$1的值为空时,"x"就不等于"henryx", 则会输出"This is not henry", 而不会出现报错
case语句
基本语法
case $var in
"值1")
若变量值为"值1",执行此程序
;;
"值2")
若变量值为"值2",执行此程序
;;
...
*)
若变量值都不是以上的值,执行此程序
;;
esac
双分号;;相当于C语言的break
最后的*)相当于C语言的dafault
最后的esac其实就是case反过来的形式, 代表case语句的结束
使用范例
输入一个数字, 若为1则输出"This is henry"; 若为"henry"则输出"This is henry"; 若上述都不是则输出"This is nothing"
[root@localhost script]# cat script.sh
#!/bin/bash
case $1 in
1)
echo "This is 1"
;;
"henry")
echo "This is henry"
;;
*)
echo "This is nothing"
;;
esac
[root@localhost script]# ./script.sh 1
This is 1
[root@localhost script]# ./script.sh henry
This is henry
[root@localhost script]# ./script.sh what
This is nothing
for循环
基本语法
for循环语法1
for (( 初始值;循环条件;变量变化))
do
程序
done
for循环语法2(更常用)
for var in value1 value2 value3
do
程序
done
使用实例
1.输入一个数字n, 输出从1加到n的总和
注意此处变量sum赋值的时候不用添加$, 但是引用的时候需要添加$
[root@localhost script]# cat ./script.sh
#!/bin/bash
sum=0
for (( i=0;i<=$1;i++))
do
sum=$[$sum+$i]
done
echo $sum
[root@localhost script]# ./script.sh 100
5050
2.打印所有输入的参数
[root@localhost script]# cat script.sh
#!/bin/bash
sum=0
for i in $1 $2 $3
do
echo $i
done
[root@localhost script]# ./script.sh henry tom terry
henry
tom
terry
while循环
基本语法
while [ 条件判断式 ]
do
循环代码
done
使用实例
从1加到100(要注意赋值表达式之间没有空格)
sum=0
i=1
while [ $i -le 100 ]
do
sum=$[$sum+$i]
i=$[$i+1]
done
echo $sum
#!/bin/bash
# Define a custom function
function count_files {
local dir=$1 #使用local来定义局部bian'liang
local ext=$2
local count=0
for file in "$dir"/*."$ext"; do
if [ -f "$file" ]; then
count=$((count+1))
fi
done
echo "$count"
}
# Call the custom function
num_files=$(count_files /path/to/directory txt)
echo "There are $num_files text files in the directory."