Chinaunix首页 | 论坛 | 博客
  • 博客访问: 927820
  • 博文数量: 146
  • 博客积分: 3321
  • 博客等级: 中校
  • 技术积分: 1523
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-29 10:32
文章分类

全部博文(146)

文章存档

2014年(2)

2013年(5)

2012年(4)

2011年(6)

2010年(30)

2009年(75)

2008年(24)

分类:

2009-07-21 16:51:19

bash中的变量修饰符

${variable:-word}     如果变量variable已经赋值且非空,则使用他的值。否则代入word
${variable:=word}     如果变量variable已经设置且值非空,就带入他的值。否则将variable的值设为
                      word。始终带入variable的值。
${variable:+word}     如果变量variable已经设置且非空,则代入他的值。否则什么也不代入。
${variable:?word}     如果变量variable已经设置且非空,则代入他的值。否则,输出word并从shell中
                      退出。如果省略了word,就会显示信息:parameter null or not set
${variable:offset}    获得变量variable值中位置从offset开始的子串,偏移为0到字符串的末尾
${variable:offset:length}    获得变量从offset位置开始长度为length的子串


along@along-laptop:~/code/shell/shell$ var=test        //首先设置var为test
along@along-laptop:~/code/shell/shell$ echo ${var:-along}
test
along@along-laptop:~/code/shell/shell$ var=                 //设置var为空
along@along-laptop:~/code/shell/shell$ echo ${var:-along}
along
along@along-laptop:~/code/shell/shell$ echo $var            //说明第一种没有给var赋值

along@along-laptop:~/code/shell/shell$ echo ${var:=along}
along
along@along-laptop:~/code/shell/shell$ echo $var       //第二种当var为空时对var会赋值 
along
along@along-laptop:~/code/shell/shell$ unset var
along@along-laptop:~/code/shell/shell$ echo ${var:-along}
along
along@along-laptop:~/code/shell/shell$ echo $var

这里第一和第二两个的区别就在于当代入word时是否给variable赋值。

子串的变量扩展

${变量%模式}       将变量值的尾部和模式进行最小匹配,并将匹配到的部分删除
${变量%%模式}       将变量值的尾部和模式进行最大匹配,并将匹配到的部分删除
${变量#模式}       将变量的值的首部与模式进行最小匹配,并将匹配到的部分删除
${变量##模式}       将变量的首部和模式进行最大匹配,并将匹配到的部分删除
${#变量}            替换为变量中的字符个数,如果是*或@长度就是位置参数的个数

along@along-laptop:~/code/shell/shell$ pathname="/usr/bin/local/bin"
along@along-laptop:~/code/shell/shell$ echo ${pathname%/bin*}
/usr/bin/local
along@along-laptop:~/code/shell/shell$ echo ${pathname%%/bin*}
/usr
along@along-laptop:~/code/shell/shell$ echo ${pathname#/usr*}
/bin/local/bin
along@along-laptop:~/code/shell/shell$ echo ${pathname##/usr*}
along@along-laptop:~/code/shell/shell$ name=along
along@along-laptop:~/code/shell/shell$ echo ${#name}
5

















阅读(1426) | 评论(1) | 转发(1) |
0

上一篇:awk提取字段

下一篇:grep匹配字符串一例

给主人留下些什么吧!~~

chinahhucai2009-08-11 15:59:25

能不能把你文章的字放大一点呢?这样就免去网友很多的操作了。呵呵