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.

Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

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

One 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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

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.