导航
当前章节: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 | if [ condition ]; then |
字符比较: == !=
整数比较:-eq -ne -lt -gt
文件比较: -f “file.txt” / -d “dir” /-x “script.sh” 文件存在/目录存在/文件可执行
布尔类型比较: condition1 -a condition2 condition1 -o condition2
case
1 | case $variable in |
for
1 | for variable in list; do |
while
1 | while [ condition ]; do |
函数
function countDown() {
echo $1
if [ $1 -gt 0 ]; then
countDown $(($1 - 1))
fi
}
countDown 5 # Prints 5 4 3 2 1