1 文件和数组
1.1 读文件并将文件内容保存到数组,遍历数组
src.f文件内容
./src/xxx_1.md
./src/xxx_2.md
./src/xxx_3.md
./src/xxx_4.md
./src/xxx_5.md
run.sh
#!/bin/bash
### read flist to array
src_array=()
while read line; do
src_array+=("$line")
done < $1
### print array
i=1
for itm in "${src_array[@]}"; do
printf "line $i content: %s\n" "$itm"
((i++))
done
exit
运行run.sh结果
2 流程控制语句
2.1 判断文件和路径是否存在
run.sh
if [[ -e "$1" ]]; then
echo "The file $1 exits."
else
echo "The file $1 does not exist."
fi
if [[ ! -d "$2" ]]; then
echo "The dir $2 does not exit."
else
echo "The dir $2 exists."
fi
运行结果
2.2 逻辑判断
*run.sh
_str="hello world"
_int=996
if [[ "$_str" == "hello world" ]]; then
echo "String Yes"
else
echo "String No"
fi
if [[ $_int != 996 ]]; then
echo "Int No"
else
echo "Int Yes"
fi
运行结果
3 shell 用户命令行参数处理
3.1 不带option
run.sh
func_print_usage(){
echo ""
echo "Usage: run.sh <user> <age> <is_ICer>"
echo ""
}
if [[ $# != 3 ]]; then
func_print_usage
elif [[ "$3" != "yes" ]]; then
echo ""
echo "You should be good good study for IC"
echo ""
else
echo ""
echo "user: $1"
echo "age: $2"
echo "is_ICer: $3"
echo ""
fi
运行结果1
运行结果2
运行结果3
3.2 带option
run.sh
func_help(){
printf "\n\n Usage:\n"
printf " -h|--help : Help usage\n"
printf " -f|--file <arg> : Specify file\n"
printf " -d|--debug : Debug mode on\n\n"
}
SHORTOPTS="h,f:,d"
LONGOPTS="help,file:,debug"
ARGS=$(getopt --options $SHORTOPTS --longoptions $LONGOPTS -- "$@")
eval set -- "$ARGS"
while true; do
case $1 in
-h|--help)
func_help
shift
exit
;;
-f|--file)
echo "file: $2"
shift 2
;;
-d|--debug)
echo "debug"
shift
;;
--)
shift
break
;;
esac
done
运行结果1
运行结果2
运行结果3
运行结果4
运行结果5
4 shell 函数
run.sh
func_1(){
echo ""
echo "func name: $0"
echo "agc1: $1"
echo "agc2: $2"
echo "agc3: $3"
echo "agc4: $4"
}
func_2(){
echo "Will be call func_1"
func_1 123 "hello world" "" 996
}
echo ""
func_2
echo ""
运行结果