Bash script进阶笔记

  1. 数组类型
arr=(1 2 3)					# 最基础的方式声明数组,用小括号(),元素之间逗号分隔
arr=([1]=10 [2]=20 [3]=30)	# 初始化时指定index
declare -a arr=(1 2 3)		# 用declare -a声明数组,小括号外面可选使用单引号、双引号
declare -a arr=(1 2 3)declare -a arr=([0]="a" [10]="b" [2]="c")	# 声明数组时指定index

echo ${arr[0]}	# output 1
echo ${arr[11]}	# not exist, output empty
  1. declare命令
    declare是bash内置命令,可为变量设置属性(值类型、访问类型等)。
    常用参数:
    -a: indexed array 数组
    -A: associative array Map类型
    -i: integer
    -r: read only
    -f: function
    -x: export,导出环境变量

  2. Map类型(关联数组)
    1)最外面是小括号(),内部元素间用空格分隔,下标用中括号[]指定。
    2)需要使用declare -A声明,不能像数组那样可省略declare -a
    3)必须提供‘下标’,下标可用数字(此时和数组类似),可以是字符串(单引号、双引号都可以)

declare -A map=(["a"]=10 ["b"]=20 ['c']=30)
echo ${map['a']}

declare -A map=([1]=10 [2]=20 [3]=30)
echo ${map[1]}
  1. glob扩展
# 目录中有3个文件
$ ls
a1  a2  b1

# [...]用括号内每个元素分别扩展,如果没有匹配的,则跳过,不会报错,不同于{...}扩展
$ ls a[123]
a1  a2

# {...}和上面的匹配对比,如果存在不匹配的,会报错提示
$ ls a{
   1,2,3}
ls: cannot access 'a3': No such file or directory
a1  a2

# a1.txt  a2.txt  b1.sh
# 多种扩展组合使用
$ ls [ab]1.{
   txt,sh,cpp}
ls: cannot access '[ab]1.cpp': No such file or directory
 a1.txt   b1.sh

# {}扩展第一项可为空,以下命令等效:cp a.txt a.txt.bak 
$ cp a.txt{
   ,.bak}

# {start..end} {start..end..step} 扩展一个范围
$ echo {
   1..5}
1 2 3 4 5
$ echo {
   1..5..2}
1 3 5
$ echo {
   3..1}
3 2 1

# 子命令扩展
date_str=$(date)
date_str=`date`  # 等价

echo $date_str

# 算数扩展
ret=$((1+2*3))
echo $ret

# 在脚本中,可以直接引用*.log
for logFile in *.log
do
	echo $logFile
done

相关推荐

  1. Bash script笔记

    2023-12-15 08:52:01       58 阅读
  2. Vue笔记(五)路由

    2023-12-15 08:52:01       57 阅读
  3. golang学习笔记——数据结构

    2023-12-15 08:52:01       57 阅读
  4. (C++)boost库笔记

    2023-12-15 08:52:01       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-15 08:52:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-15 08:52:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-15 08:52:01       82 阅读
  4. Python语言-面向对象

    2023-12-15 08:52:01       91 阅读

热门阅读

  1. Python多线程编程:竞争问题的解析与应对策略

    2023-12-15 08:52:01       53 阅读
  2. windows MinGW C语言编译器安装及环境变量配置教程

    2023-12-15 08:52:01       56 阅读
  3. LeetCode //C - 605. Can Place Flowers

    2023-12-15 08:52:01       60 阅读
  4. kafka3.X集群安装(不使用zookeeper)

    2023-12-15 08:52:01       52 阅读
  5. vue-quill-editor上传图片base64转化为img标签

    2023-12-15 08:52:01       61 阅读
  6. ubuntu-base 20.04防火墙配置方法

    2023-12-15 08:52:01       59 阅读
  7. 解释 Git 的基本概念和使用方式

    2023-12-15 08:52:01       58 阅读
  8. Webservice--HTTP,SOAP协议区别

    2023-12-15 08:52:01       45 阅读