Bourne Shell Tip: Use Subshells Interactively

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:

  1. Use cd ../.. followed by youtube-dl or wget and then cd back into place
  2. Same as step 2 but using pushd/popd rather than cd (or cd/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.

CC BY-SA 4.0 Bourne Shell Tip: Use Subshells Interactively by Stephan Sokolow is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

This entry was posted in Geek Stuff. Bookmark the permalink.

1 Response to Bourne Shell Tip: Use Subshells Interactively

  1. Nesetalis says:

    Tricksy tricksy shell bashing! Thank you very much.

Leave a Reply

Your email address will not be published. Required fields are marked *

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution under the same terms as the associated post.

All comments are moderated. If your comment is generic enough to apply to any post, it will be assumed to be spam. Borderline comments will have their URL field erased before being approved.