What is the use case of noop [:] in bash?

后端 未结 12 942
滥情空心
滥情空心 2020-12-12 13:07

I searched for noop in bash (:), but was not able to find any good information. What is the exact purpose or use case of this operator?

I tried following and it\'s w

12条回答
  •  悲&欢浪女
    2020-12-12 13:13

    I use it for if statements when I comment out all the code. For example you have a test:

    if [ "$foo" != "1" ]
    then
        echo Success
    fi
    

    but you want to temporarily comment out everything contained within:

    if [ "$foo" != "1" ]
    then
        #echo Success
    fi
    

    Which causes bash to give a syntax error:

    line 4: syntax error near unexpected token `fi'
    line 4: `fi'
    

    Bash can't have empty blocks (WTF). So you add a no-op:

    if [ "$foo" != "1" ]
    then
        #echo Success
        :
    fi
    

    or you can use the no-op to comment out the lines:

    if [ "$foo" != "1" ]
    then
        : echo Success
    fi
    

提交回复
热议问题