https://blog.csdn.net/w918589859/article/details/108752592

# shell 脚本

test.sh
1
2
#!/bin/bash
echo "Hello World !"

运行:

运行
1
2
chmod +x ./test.sh  #使脚本具有执行权限
./test.sh #执行脚本

# shell 变量:

数字字母下划线,不能以数字开头,区分大小写,常量一般大写
赋值的时候等号两侧避免使用空格

赋值
1
variable_name=value

使用一个定义过的变量,只要在变量名前面加美元符号即可

使用变量
1
2
3
your_name="qinjx"
echo $your_name
echo ${your_name}

只读变量 ——readonly

只读变量
1
2
3
4
5
#!/bin/bash

myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.runoob.com"

删除变量

删除变量
1
unset variable_name

变量类型

  • 字符串变量:单引号或双引号
  • 整数变量:用 declare 或 typeset 命令来声明整数变量
  • 数组变量:
数组变量
1
2
3
4
my_array=(1 2 3 4 5)
declare -A associative_array # 声明一个关联数组
associative_array["name"]="John"
associative_array["age"]=30
  • 环境变量:比如 PATH、HOME、USER 等,用 export 命令来设置环境变量
  • 特殊变量: 有一些特殊变量在 Shell 中具有特殊含义,例如 $0 表示脚本的名称,$1, $2, 等表示脚本的参数。$# 表示传递给脚本的参数数量,$? 表示上一个命令的退出状态等

# Shell 字符串

字符串可以用单引号,也可以用双引号,也可以不用引号

  • 单引号:单引号中的字符原样输出,不会进行变量替换、命令替换、参数替换等
  • 双引号:双引号中的字符会进行变量替换、命令替换、参数替换等,但不会进行文件名扩展和路径名扩展
  • 不使用引号:如果字符串中没有空格或特殊字符,可以直接使用,否则需要使用引号
字符串
1
2
3
4
5
6
7
8
9
10
your_name="runoob"
# 使用双引号拼接
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1

# 使用单引号拼接
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2 $greeting_3

输出结果为
hello, runoob ! hello, runoob !
hello, runoob ! hello, ${your_name} !

获取字符串长度

获取字符串长度
1
2
string="abcd"
echo ${#string} # 输出 4

变量为字符串时,$

Edited on

Give me a cup of [coffee]~( ̄▽ ̄)~*

NoResponse WeChat Pay

WeChat Pay

NoResponse Alipay

Alipay

NoResponse PayPal

PayPal