阿川CH
学海无涯,上栽上栽!
Toggle navigation
阿川CH
主页
归档
标签
shell变量操作
Linux
Shell
常用操作
2018-03-09 17:51:27
0
0
0
cqc
Linux
Shell
常用操作
# shell变量操作 ## 字符串长度 `${#var}` ## 头部截取 把字符中头部符合`mode`的部分删除 懒惰模式:`${var#mode}` 贪婪模式:`${var##mode}` ``` var="abcabcabc" echo ${var#*a} bcabcabc echo ${var##*a} bc ``` ## 尾部截取 把字符中尾部符合`mode`的部分删除 懒惰模式:`${var%mode}` 贪婪模式:`${var%%mode}` ``` var="abcabcabc" echo ${var%%c*} ab echo ${var%c*} abcabcab ``` ## 替换 `${var/old_string/new_string}`:将字符串中首个`old_string`替换为`new_string` `${var//old_string/new_string}`:将字符串中所有`old_string`替换为`new_string` ## slice `${var:start_index:length}` ```bash var="0123456789" echo ${var:3} 3456789 echo ${var:3:3} 345 # 后几位不要。 length的公式为:总长度-start_index-不要的位数 echo ${var:3:${#var}-3-2} 34567 ``` ## 判空 转 默认值 `${var-default}`:当变量未设置时,取default作为表达式的值 `${var:-default}`:当变量未设置或空串时,取default作为表达式的值 ``` [cqc@emr-header-1 ~]$ unset var [cqc@emr-header-1 ~]$ echo ${var-default} default [cqc@emr-header-1 ~]$ var="" [cqc@emr-header-1 ~]$ echo ${var-default} [cqc@emr-header-1 ~]$ echo ${var:-default} default ``` ## 判非空 转 默认值 `${var+default}`:当变量已设置时,取default作为表达式的值 `${var:+default}`:当变量已设置且非空串时,取default作为表达式的值 ``` [cqc@emr-header-1 ~]$ unset var [cqc@emr-header-1 ~]$ echo ${var+val} [cqc@emr-header-1 ~]$ var="test" [cqc@emr-header-1 ~]$ echo ${var+val} val [cqc@emr-header-1 ~]$ var="" [cqc@emr-header-1 ~]$ echo ${var+val} val [cqc@emr-header-1 ~]$ echo ${var:+val} [cqc@emr-header-1 ~]$ ``` ## 赋值 `var=${str=default}`:当str变量未设置时,将default同时赋值给var和str,否则执行var=${str} `var=${str:=default}`:当str变量未设置或为空串时,将default同时赋值给var和str,否则执行var=${str} ``` [cqc@emr-header-1 ~]$ unset str [cqc@emr-header-1 ~]$ var=${str=default} [cqc@emr-header-1 ~]$ echo ${var} default [cqc@emr-header-1 ~]$ echo ${str} default [cqc@emr-header-1 ~]$ str="" [cqc@emr-header-1 ~]$ var=${str=default} [cqc@emr-header-1 ~]$ echo ${str} [cqc@emr-header-1 ~]$ echo ${var} [cqc@emr-header-1 ~]$ [cqc@emr-header-1 ~]$ str="test" [cqc@emr-header-1 ~]$ var=${str=default} [cqc@emr-header-1 ~]$ echo ${var} test [cqc@emr-header-1 ~]$ echo ${str} test [cqc@emr-header-1 ~]$ [cqc@emr-header-1 ~]$ str="" [cqc@emr-header-1 ~]$ var=${str:=default} [cqc@emr-header-1 ~]$ echo ${str} default [cqc@emr-header-1 ~]$ echo ${var} default ```
上一篇:
HDFS不同集群迁移实践
下一篇:
Kafka常用排查命令
文档导航