1.脚本执行的4种方法#!/bin/bash # test.sh # 这里借助SHLVL这个变量,SHLVL可以显示shell的层级, # 每启动一个shell,这个值就加1 echo "shell level :$SHLVL" echo "hello world!"
总结:注意看SHLVL的值,前3种方式都在子shell中执行(sh除外),第4种在当前shell种执行。 2.调试脚本bash -x script.sh 跟踪调试脚本 root@localhost:/tmp# bash -x test.sh + echo 'shell level :2' shell level :2 + echo 'hello world!' hello world! -x 打印所执行的每一行命令及当前状态 set -x:在执行是显示参数和命令 set +x:禁止调试 set -v :当命令进行读取时显示输入 set +v :当命令进行读取时禁止打印输入 3.输出格式化1.C语言风格格式化输出#!/bin/bash printf " % -5s %-10s %-4s\n" NO. Name Mark printf " % -5s %-10s %-4.2f\n" 1 joe 80.55 printf " % -5s %-10s %-4.1f\n" 2 joe 80.5 printf " % -5s %-10s %-4.3f\n" 3 joe 80.500 2.echo1.不换行 echo -n "hello world" 2.转义 echo -e "hello\t\tworld" 3.彩色输出 颜色 重置 黑 红 绿 黄 蓝 紫 青 白 前景色 0 30 31 32 33 34 35 36 37 背景色 0 40 41 42 43 44 45 46 47 echo -e "\e[1;31m This is red test \e[0m" 4.数据类型1.字符串获取字符串长度 echo ${#str} 2.数组数组的定义 方法一: arr=(1 2 3 4 5) 方法二: arr[0]=1 arr[1]=2 arr[2]=3 echo ${arr[*]} 1 2 3 打印数组中的值 root@localhost:~# arr=(1 2 3 4 5) 3.关联数组普通数组只能使用整数作为索引值,而关联数组可以使用任意文本作为索引值(有点类似于Python中的字典,不知道这样理解对不对),关联数组只在bash 4.0以上支持。 bash -version 关联数组的定义和使用 root@localhost:~# declare -A person root@localhost:~# person=([name]="Wang" [age]=18) root@localhost:~# echo ${person[name]} Wang root@localhost:~# echo ${person[age]} 18 root@localhost:~# echo ${person[*]} Wang 18 5.重定向符号 含义 用法 例 < 标准输入 从文件中输入 wc -l file.txt > 标准输出 目标文件不存在会新建一个;目标文件存在会覆盖原内容 echo "" > /var/www/html/index.php >> 追加到文件 目标文件不存在会新建一个;目标文件存在会在文件末尾追加 echo "add text" >> file.txt 6.变量1.只读变量#!/bin/bash readonly hours_per_day=24 hours_per_day=12 更改变量会触发异常 2.展开运算符
|
|