New FAMILUG

The PyMiers

Tuesday 4 March 2014

[bash] Brace expansion

$ for i in {1..11}; do echo hostxxx-$i; done                                                               
hostxxx-1
hostxxx-2
hostxxx-3
hostxxx-4
hostxxx-5
hostxxx-6
hostxxx-7
hostxxx-8
hostxxx-9
hostxxx-10
hostxxx-11
$ for i in {01..11}; do echo hostxxx-$i; done                                                             
hostxxx-01
hostxxx-02
hostxxx-03
hostxxx-04
hostxxx-05
hostxxx-06
hostxxx-07
hostxxx-08
hostxxx-09
hostxxx-10
hostxxx-11



Giả sử bạn cần thao tác với các host có tên cùng scheme và đánh số như trên, dùng bash expansion giúp giải quyết vấn đề sinh số liên tục. Bash đủ thông minh để hiểu bạn cần 01 hay 1.
Ví dụ trên nói lên tất cả.

Hết :3

2 comments:

  1. $ echo {1..10..2}
    1 3 5 7 9

    với
    2 là khoảng cách giữa các phần tử được expand

    ReplyDelete
  2. Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

    ReplyDelete