What’s the difference between

[ -f ~/.fzf.bash ] && source ~/.fzf.bash

and

if [ -f ~/.fzf.bash ]; then
    source ~/.fzf.bash
fi

Both snippets achieve the same goal: they source ~/.fzf.bash if the file exists. However, there are differences in syntax and style:

1. Conditional Execution with &&

[ -f ~/.fzf.bash ] && source ~/.fzf.bash
  • Description: This is a compact one-liner that uses a short-circuit logical AND. If the file test ([ -f ~/.fzf.bash ]) is true, it runs source ~/.fzf.bash.
  • Use Case: Preferred for simplicity and brevity when you want to perform a single action based on a condition.

2. if-then-fi Structure

if [ -f ~/.fzf.bash ]; then
    source ~/.fzf.bash
fi
  • Description: This is a more traditional if statement, often used when there is more than one action to perform or when you want the structure to be more readable.
  • Use Case: Better for readability, especially if you plan to add additional commands inside the if block.

Summary

  • First Approach: More concise, suitable for simple, single-line conditions.
  • Second Approach: More readable, preferred for longer scripts or when multiple commands need to be executed conditionally.

Both are functionally equivalent for this use case, so it comes down to personal preference or coding standards in your environment.