1.脚本中的传参
非交互模式下:从shell中向脚本内部传参。
$0 :脚本本身名称
$1 :脚本后输入的第一串字符
$2 :脚本后输入的第二串字符
$3 :脚本后输入的第三串字符
$* :脚本后输入的所有字符 (eg: “apple banana orange”)
$# :脚本后输入的字符串个数
$@ :脚本后输入的所有字符 (eg: “apple” “banana” “orange”)
交互式传参:
read -p “。。。。。” 变量 -p 后跟字符,字符后跟变量名。
read -p "input: " hello (hello 为变量名)
echo $hello
2.函数
除去重复的部分:
#!/bin/bash
action()
{
if “$1”==“exit” &&{
exit
} || {
read -p "input your name: " name
echo $name
action
}
}
action
循环输入名字,直到输入exit退出循环。
3.for语句
for :定义变量
do :做事
done :结束
示例:for WESTOS in java linux c
do
echo $WESTOS
sleep 1
done
显示:java linux c
for ((num=0;num<10;num++))
do
echo $num
done
示例:用脚本检测10台与当前主机连接的主机网络是否通畅,如果网络通畅显示主机ip列表。
#!/bin/bash
for ip in 172.25.254.{10…20}
do
ping -c1 -w1 $ip &> /dev/null && {
echo $ip >> file
}
done
4.条件语句
1.while…do :条件为真执行动作
while
do
done
while true
do
read -p "input num: " num
[ “$num” = “exit” ] && {
exit
} ||
echo $num
done
2.until…do :条件为假执行动作
3.if…then :条件判断语句
if [ -L “$1” ] ## 可以多次判断语句
then
echo “$1 is link file”
elif [ -d " $1" ]
then
echo “$2 is dir”
else ## 所有判断都不成立
echo unknown
fi
示例
check_file.sh
要求:input: file “file is not exist” “file is a file” " file is a direcory" 此脚本会一直执行直到用户输入exit退出。
ACTION(){
read -p "input: " file
[ "$file" = "exit" ] && {
exit
} || {
[ -e "$file" ] || {
echo $file is not exist
}
[ -f "$file" ] && {
echo " $file is file"
}
[ -d "$file" ] && {
echo " $file is dir"
}
}
ACTION
}
ACTION
contiue :终止此次循环进入下一个循环
break :终止当前循环
exit :退出脚本