-
功能介绍
字符串是多个字符组成的集合。多个也可以是0或者大于等于1的个数。首先了解常见字符ascii码如A B C 1 2 3 。多个字符组成集合,用双引号,单引号或者直接放到一起。
备注:
1. ASCII 码表 - cppreference.com
2. 中文其他语言的字符不在这里介绍
-
语法格式
序号 | 格式 | 说明 |
---|---|---|
1 | 变量名='字符串’ | 单引号 (') 用于保留字符的字面含义,特殊字符在单引号里面,都会变为普通字符,例如 *、$、反斜杠 (\) 等。 |
2 | 变量名="字符串" | 双引号 (") 比单引号 (') 宽松。在双引号中,反引号 (`)、$、反斜杠 (\) 三个特殊字符会被 Bash 自动扩展。$ 符号用于引用变量,反引号 (`) 用于执行子命令。反斜杠 (\) 在双引号之中用来转义。 |
3 | 变量名=字符串 | 适用于连续的字符串,字符串中不能有空格类的字符。反斜杠(\)会被忽略,$ 符号用于引用变量,反引号 (`) 用于执行子命令 |
-
实例
1.变量名='字符串’
单引号 (') 用于保留字符的字面含义,特殊字符在单引号里面,都会变为普通字符,例如 *、$、反斜杠 (\) 等。
renhl@verygood:~/usb$ str=ABC;str2='abc${str}`pwd` $(ls) 123';cd ..;str=123;echo $str2 #单引号中的命令pwd和ls,变量取值${str} 都没有被执行
abc${str}`pwd` $(ls) 123
renhl@verygood:~$
2.变量名="字符串"
双引号 (") 比单引号 (') 宽松。在双引号中,反引号 (`)、$、反斜杠 (\) 三个特殊字符会被 Bash 自动扩展。$ 符号用于引用变量,反引号 (`) 用于执行子命令。反斜杠 (\) 在双引号之中用来转义。
renhl@verygood:~/usb$ str=ABC;str2="abc${str}`pwd` $(ls) 123";cd ..;str=456;echo $str2 #在str2被赋值时,${str},pwd和ls都被执行
abcABC/home/renhl/usb 1.txt awk_help.txt cut_help.txt grep_help.txt head_help.txt sed_help.txt tail_help.txt tr_help.txt 123
renhl@verygood:~$ cd usb/
renhl@verygood:~/usb$ ls
1.txt awk_help.txt cut_help.txt grep_help.txt head_help.txt sed_help.txt tail_help.txt tr_help.txt
renhl@verygood:~/usb$
3.变量名=字符串
适用于连续的字符串,字符串中不能有空格类的字符。反斜杠(\)会被忽略,$ 符号用于引用变量,反引号 (`) 用于执行子命令
renhl@verygood:~/usb$ str=ABC;str2=abc${str}`pwd`$(ls)123;cd ..;str=456;echo $str2 #变量读取,pwd和ls命令被执行了
abcABC/home/renhl/usb1.txt awk_help.txt cut_help.txt grep_help.txt head_help.txt sed_help.txt tail_help.txt tr_help.txt123
renhl@verygood:~$ cd usb/
renhl@verygood:~/usb$ ls
1.txt awk_help.txt cut_help.txt grep_help.txt head_help.txt sed_help.txt tail_help.txt tr_help.txt
renhl@verygood:~/usb$ str=ABC;str2=abc ${str} #字符串中间不能有空格,空格也是语句间的分隔符
ABC: command not found
renhl@verygood:~/usb$