Suppose you’re using your favourite Bourne-style shell (be it bash, zsh, or whatever else you fancy) and you want to save a video into a folder two levels up the directory tree.
Do you:
- Use
cd ../..
followed byyoutube-dl
orwget
and thencd
back into place - Same as step 2 but using
pushd
/popd
rather thancd
(orcd
/popd
if you’ve got the right shopts set)
Both work… but there’s something even more useful you can do.
(cd ../..; youtube-dl [whatever])
By wrapping a series of commands in parentheses, you run them in a subshell. This means that any state changes like setting environment variables or changing the current working directory are forgotten when the subshell exits.
A subshell is great for off-the-cuff interactive one-liners because, just like with a shell script, you don’t have to count your pushd calls or be careful with how you modify the shell environment. It just doesn’t affect the parent shell’s state unless you do extra work.
I love to combine them with Tab completion (denoted by T), Ctrl+V (denoted by V), and a shell function that wraps up my favorite downloaders like youtube-dl and fanfic2html so I can type this:
(cd ~/inT/ViT/NoT; dl V)
…and get this without having to reset my working directory afterwards:
(cd ~/incoming/Videos/Nostalgia\ Critic; dl http://blip.tv/nostalgiacritic/nostalgia-critic-conan-part-02-3136650)
It’s even nicer when I want to fiddle around with environment variables too.
Bourne Shell Tip: Use Subshells Interactively by Stephan Sokolow is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Tricksy tricksy shell bashing! Thank you very much.