A context is like the rooms in a flat. In general, each room has a separate purpose – bedroom for privacy, kitchen for cooking, drawing-room for enjoying a movie with family… What if you could maintain contexts of your shell the same way for different tasks? Say, you need to export certain variables and jump to a particular directory to start working a development project or run some particular commands before running a software. How do you automate all the initial set up?

The drop-down terminal AltYo is quite helpful for this. It retains the state of each tab, available at your beck and call. However, the states are not stored across reboots. Also, a way to load any context on-demand is much more convenient.

By this time you might be thinking, why can’t I use a shell script to do those? You are close! But there’s a caveat: a shell script runs within a new instance of the shell. So if you are exporting some variables, they will not be retained by the time the script completes.

source is your friend! source is a bash shell builtin that executes the content of a file (even non-executable plain-text) in the same shell. To get some more info on source:

$ type source source is a shell builtin $ help source source: source filename [arguments] Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. Exit Status: Returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read.

And shockingly under-used it is! source is available for bash as well as fish shell (but not exactly as source in this case).

bash

Here’s my context file (named bashcontext) for a project that I am working on:

export VAR=abc export LOGLEVEL=4 export CC=arm-linux-gcc cd ~/MyProjects/Current

Let’s source and see how it works:

~$ source bashcontext ~/MyProjects/Current$ echo $LOGLEVEL 4

Note that the directory has switched to my project directory and the variables are set. There is a shortcut to source as well, a . (dot):

~$ . bashcontext

fish

In fish, only . works. Here’s the context file in fish lingo (named fishcontext), which does the same job:

set VAR abc set LOGLEVEL 4 set CC arm-linux-gcc cd ~/MyProjects/Current

Let’s source and check:

~> . fishcontext ~/MyProjects/Current> echo $CC arm-linux-gcc

You can maintain as many context files you want to initialize all your tasks. Just source the right file and start working instantly without having to remember (and run) the same commands again and again!