Why is there a logical operation in bash_profile
Hi, I was taking a look at my bash_profile today to clean it up and noticed this.
[[ -f ~/.bashrc ]] && . ~/.bashrc
can anyone explain to me what that does? Why compare two values for no reason?
About this post
- Posted
- Archived
- Score
- 8 · 100% up
- Kind
- Text
- ID
- p4e01
9 comments
It's not comparing two values, it's a list operator.
From man bash:
In this case, the first command is the test to see if ~/.bashrc exists, to avoid an error trying to source a non-existent file.
You'll sometimes see scripts use the OR control to exit on a failure of a test or another command, e.g.
If somefile doesn't exist, stop here with an exit status indicating error!
thanks for that
More fully, its an example of short-circut evaluation which you will see in many programming languages. This is a trick built around an optimization, since you only evaluate far enough to get a final value.
The basic idea is when
foois false,foo && Truewill always be false and if foo is True,foo || anythingwill still be True. The trick is that segments in the statement don't get resolved until needed.So with:
if
[[ -f ~/.bashrc ]]is false, there is no point to evaluating the rest of the expression, we knowfalse && anythingis false, and the rest of the expression won't be evaluated. If its true, the expression does rely on the. ~/.bashrcpart and thus gets evaluated.Note that
[[is technically (it will be a built in) a command, and the&&and||operators operate on the return codes of commands.Here's an example from the wiki:
myfuncwill never run. Important gotcha if plan on relying on side-effects in myfunc.It's short for
"[[ -f ]]" checks if a file (.bashrc in your home, in this case) exists (and is a file, "-d" is for directories).
source .bashrc "loads" .bashrc and everything defined therein into the current environment.
can someone explain why it uses double brackets instead of one?
What is the difference between double and single square brackets in bash?
http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression
I always forget that. And when I look it up its gone again in less than a week.
I added a comment above that line in mine that says "I don't know what this does. Don't touch it. "
I guess I can change that now. Then maybe learn some bash.