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 working like this for me:
[mandy@root]$ a=11
[mandy@root]$ b=20
[mandy@root]$ c=30
[mandy@root]$ echo $a; : echo $b ; echo $c
10
30
Please let me know, any use case of this operator in real time or any place where it is mandatory to use it.
You would use
:
to supply a command that succeeds but doesn't do anything. In this example the "verbosity" command is turned off by default, by setting it to:
. The 'v' option turns it on.Sometimes no-op clauses can make your code more readable.
That can be a matter of opinion, but here's an example. Let's suppose you've created a function that works by taking two unix paths. It calculates the 'change path' needed to cd from one path to another. You place a restriction on your function that the paths must both start with a '/' OR both must not.
Some developers will want to remove the no-op but that would mean negating the conditional:
Now -in my opinion- its not so clear from the if-clause the conditions in which you'd want to skip doing the function. To eliminate the no-op and do it clearly, you would want to move the if-clause out of the function:
That looks better, but many times we can't do this; we want the the check to be done inside the function.
So how often does this happen? Not very often. Maybe once or twice a year. It happens often enough, that you should be aware of it. I don't shy away from using it when I think it improves the readability of my code (regardless of the language).
I use it for if statements when I comment out all the code. For example you have a test:
but you want to temporarily comment out everything contained within:
Which causes bash to give a syntax error:
Bash can't have empty blocks (WTF). So you add a no-op:
or you can use the no-op to comment out the lines:
One use is as multiline comments, or to comment out part of your code for testing purposes by using it in conjunction with a here file.
Don't forget to use quotes around
EOF
so that any code inside doesn't get evaluated, like$(foo)
. It also might be worth using an intuitive terminator name likeNOTES
,SCRATCHPAD
, orTODO
.If you use
set- e
then|| :
is a great way to not exit the script if a failure happens (it explicitly makes it pass).Ignore
alias
argumentsSome times you want to have an alias that doesn't take any argument. You can do it using
:
: