0
点赞
收藏
分享

微信扫一扫

shell脚本中的花括号扩展

shell脚本中的花括号扩展

  1. 在shell脚本中可以在花括号中使用一组以逗号分隔的字符串或者字符串序列来进行字符串扩展,最终输出的结果为以空格分隔的字符串(整数也可)

    [root@mao_aliyunserver bin]# echo {1..10}
    1 2 3 4 5 6 7 8 9 10
    [root@mao_aliyunserver bin]# echo {a..z}
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    
  2. 使用花括号扩展时花括号不可以被单引号或者双引号引用

    [root@mao_aliyunserver bin]# echo "{1..10}"
    {1..10}
    [root@mao_aliyunserver bin]# echo '{1..10}'
    {1..10}
    
  3. 如果使用字符串序列后面跟一个步长(整数),默认值为1或-1

    [root@mao_aliyunserver bin]# echo {1..10..2}
    1 3 5 7 9
    [root@mao_aliyunserver bin]# echo {a..z..2}
    a c e g i k m o q s u w y
    
  4. 使用花括号扩展时在花括号前面和后面都可以添加可选字符串,且花括号扩展支持嵌套

    [root@mao_aliyunserver bin]# echo a{a..d}c
    aac abc acc adc
    [root@mao_aliyunserver bin]# echo 开{炮,礼{品,花,盒}}了
    开炮了 开礼品了 开礼花了 开礼盒了
    
  5. 花括号扩展的简单应用

    #批量生成文件
    [root@mao_aliyunserver test]# ll
    total 0
    [root@mao_aliyunserver test]# touch ./{a..e}.txt
    [root@mao_aliyunserver test]# ll
    total 0
    -rw-r--r-- 1 root root 0 Feb 14 22:44 a.txt
    -rw-r--r-- 1 root root 0 Feb 14 22:44 b.txt
    -rw-r--r-- 1 root root 0 Feb 14 22:44 c.txt
    -rw-r--r-- 1 root root 0 Feb 14 22:44 d.txt
    -rw-r--r-- 1 root root 0 Feb 14 22:44 e.txt
    
    #备份文件
    [root@mao_aliyunserver test]# ll
    total 0
    -rw-r--r-- 1 root root 0 Feb 14 22:45 test.txt
    [root@mao_aliyunserver test]# cp test.txt{,.bak}
    [root@mao_aliyunserver test]# ll
    total 0
    -rw-r--r-- 1 root root 0 Feb 14 22:45 test.txt
    -rw-r--r-- 1 root root 0 Feb 14 22:46 test.txt.bak
    
    #类似备份文件的需要几个相似参数的命令都可以用花括号扩展,例如重命名
    [root@mao_aliyunserver test]# ll
    total 0
    -rw-r--r-- 1 root root 0 Feb 14 22:46 test.txt.bak
    [root@mao_aliyunserver test]# mv test.txt{.bak,}
    [root@mao_aliyunserver test]# ll
    total 0
    -rw-r--r-- 1 root root 0 Feb 14 22:46 test.txt
    
举报

相关推荐

0 条评论