ZhangZhihui's Blog  

In shell (especially POSIX shells like sh, bash, dash, zsh), : is a builtin command called the null command.

What it does

  • Does nothing

  • Always succeeds (returns exit status 0)

:
echo $?
# 0

Why it’s useful

Even though it does nothing, : is surprisingly handy.


1. Placeholder in scripts

When syntax requires a command but you don’t want to do anything yet:

if condition; then
    :
fi

2. Infinite loops

Common idiom:

while :; do
    echo "Running..."
    sleep 1
done

(: always succeeds, so the loop never ends.)


3. Default action in conditionals

When you want to explicitly do nothing:

case "$var" in
    yes) echo "Yes" ;;
    no)  echo "No" ;;
    *)   : ;;
esac

4. Variable expansion with side effects

Often used to safely trigger parameter expansion:

: "${VAR:=default}"
  • Sets VAR to default if it’s unset or empty

  • No output, no side effects besides assignment


5. Redirecting without running a command

Since : does nothing, it’s useful with redirections:

: > file.txt        # truncate or create file
: >> logfile.log    # append (touch-like)

6. Alternative to true

: is faster and more portable than calling /bin/true:

while :; do ...; done

Summary

Feature:
Type Shell builtin
Effect Does nothing
Exit status Always 0
Common uses Loops, placeholders, parameter expansion, redirection

 

posted on 2025-12-15 23:29  ZhangZhihuiAAA  阅读(0)  评论(0)    收藏  举报