Linux: What is : in bash and what is its impact of use ?

Today we will look what is : in bash shell in Linux or Unix and how to use it, and what is its impact if used.

What is : (colon) in BASH ?
: is a special built-in which was built into the shell which resembles to function true on Linux systems.
Hence a user can either use TRUE or “:”.

Difference between true and : then ?
: is considered slightly better than true since it is a special bultin made into the bourne shell and hence it is more portable with ancient Bourne-derived shells.
True is used for ease of understanding and is derived later on, in most of the shells which return 0 or true on exit. The same task is carried out by : with more portability or support with ancient shells than true.

What is the impact of use ?
The impact of “:” is that –> it returns true in current statement execution and the next statements after “:” gets skipped with return status true (i.e. with 0 exit status).

How to use it ?
Lets see two examples of “:” usage:

1. Used as true or 1.

[root@nglinux ~]# export i=1; while(:) do echo "Enter 0 to quit"; read i; if [ $i -eq 0 ];then break;fi;  done
Enter 0 to quit

-bash: \[: -eq: unary operator expected
Enter 0 to quit

-bash: \[: -eq: unary operator expected
Enter 0 to quit
0

The same effect if we use true.

[root@nglinux ~]# export i=1; while(true) do echo "Enter 0 to quit"; read i; if [ $i -eq 0 ];then break;fi;  done
Enter 0 to quit

-bash: \[: -eq: unary operator expected
Enter 0 to quit

-bash: \[: -eq: unary operator expected
Enter 0 to quit
0
[root@nglinux ~]# 

 

2. Used as a comment in a set of statements.

[root@nglinux ~]# for i in {1..10}; do  if (($i < 5)); \
then : this is comment; else echo "Test $i"; : Not print; fi; done
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
[root@nglinux ~]# 

In the above example, i ran a loop from 1 to 10, and you can see the text after “:” is not executed since it returns true and skip execution of current statement.

I hope you liked the article and the concept of special bash built in “:”.

Do subscribe to our blog for great Linux or Unix learning or contact me to be part of this blog by posting your own articles.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments