Use bash tricks to help save keystrokes and time
There are some bash tricks that can be incredibly helpful. Here's a collection of those that I have encountered.
||
for fallback commandsAn example:
source my_env/bin/activate || conda activate my_env || source activate my_env
Where did this come up? In my continuous integration pipelines, I try to maintain the same syntax between pipelines (e.g. GitHub Actions and Azure Pipelines.) However, as of 2020, Azure Pipelines doesn't play well with conda activate
, and requires that I use source activate
. As such, in order to use the same bash scripts that need to activate an environment, I used the bash ||
syntax to create a fallback command for the conda activate
command. If the conda activate
command fails, the source activate
command will be executed.
The commands are executed in order from left to right. One thing neat is that there will be an exit code of 0
, which by bash historical convention signifies "success", as soon as one of the commands succeeds. If all three fail, there will be a non-zero exit code, which, depending on your system, should terminate further execution.
Create shell command aliases for your commonly used commands
Shell aliases can save you keystrokes, which save time. That time saved is compound interest over long time horizons!
Shell aliases are easy to create. In your shell initializer script, use the following syntax, using ls
being aliased to exa
with configuration flags at the end as an example:
alias ls="exa --long"
Now, typing ls
at the shell will instead execute exa
! (To know what is exa
, see Install a suite of really cool utilities on your machine using homebrew.)
In order for these shell aliases to take effect each time you open up your shell, you should ensure that they get sourced in your shell initialization script (see: Take full control of your shell environment variables for more information). You have one of two options:
.zshrc
or .bashrc
(or analogous) file, or~/.aliases
, which you source inside your shell initialization script file (i.e. .zshrc
/.bashrc
/etc.)I recommend the second option as doing so means you'll be putting into practice the philosophy of having clear categories of things in one place.
In my dotfiles repository, I have a .shell_aliases
directory which contains a full suite of aliases that I have installed.
Other external links that showcase shell aliases that could serve as inspiration for your personal collection include:
And finally, to top it off, Twitter user @ctrlshifti suggests aliasing please to sudo for a pleasant experience at the terminal:
alias please="sudo"
# Now you type:
# please apt-get update
# please apt-get upgrade
# etc...