导航
当前章节:shell脚本
原文链接:shell脚本
上一章节:gcc编译器
下一章节:gdb程序调试工具
目录:Linux程序设计
shell
介绍
shell是linux自带的脚本语言,通过shell可以实现高效的自动化服务,方便系统的配置和管理。
shell中可以直接运行命令行,因此可以创建shell脚本将一些命令序列整合
shell文件以.sh标志,通过/bin/bash x.sh执行
当然可以通过首行加解释器指令 #!/bin/bash然后可以通过./x.sh直接执行
dash和bash
dash和bash都是linxu的shell解释器,dash速度和资源性能更好,bash是dash的扩展增强
变量
shell变量
${var} or $var
自带变量:
• HOME - The path to your home directory
• PATH - A list of directories where the shell looks for executable files
• PS1 - The shell prompt
• LANG - The default language locale
• USER - Your username
• OSTYPE - The operating system type
• HOSTNAME - The network name of your server
位置参数作为脚本传入的参数 $1-$9,$#表示传入参数的个数 $*一个整串 $@多个串,可遍历
$0表示脚本名称
shift语句删除首个参数
if语句
1 2 3 4 5 6 7 8 9 10 11 | if [ condition ]; then commands fi if [ condition1 ]; then If block elif [ condition2 ]; then Elif block else Else block fi |
字符比较: == !=
整数比较:-eq -ne -lt -gt
文件比较: -f “file.txt” / -d “dir” /-x “script.sh” 文件存在/目录存在/文件可执行
布尔类型比较: condition1 -a condition2 condition1 -o condition2
case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | case $variable in pattern1) commands ;; pattern2) commands ;; *) default commands ;; esac case $animal in d*g) #匹配d开头g结尾 echo "Animal name starts with d and ends with g" ;; [aeiou]*) # 匹配元音开头 echo "Animal name starts with a vowel" ;; esac case $var in a|b|c) echo "var is a, b or c";; esac |
for
1 2 3 | for variable in list; do commands done |
while
1 2 3 | while [ condition ]; do commands done |
函数
function countDown() {
echo $1
if [ $1 -gt 0 ]; then
countDown $(($1 - 1))
fi
}
countDown 5 # Prints 5 4 3 2 1