Adding a zero to single digit variable

前端 未结 10 2090
星月不相逢
星月不相逢 2021-01-30 05:31

Trying to add a zero before the varaible if it\'s less than 10 and create said directory. I can\'t seem to get the zero to add correctly. Keeps resulting in making 02.1.20

10条回答
  •  -上瘾入骨i
    2021-01-30 06:21

    In Bash 4, brace range expansions will give you leading zeros if you ask for them:

    for i in {01..31}
    

    without having to do anything else.

    If you're using earlier versions of Bash (or 4, for that matter) there's no need to use an external utility such as seq:

    for i in {1..31}
    

    or

    for ((i=1; i<=31; i++))
    

    with either of those:

    mkdir "$path/02.$(printf '%02d' "$i").2011"
    

    You can also do:

    z='0'
    mkdir "$path/02.${z: -${#i}}$i.2011"
    

    Using paxdiablo's suggestion, you can make all the directories at once without a loop:

    mkdir "$path"/02.{0{1..9},{10..31}}.2011
    

提交回复
热议问题