~/blog|
Published on

Backup and Restore Visual Studio Code Extensions from the Command Line

Authors

I maintain my own dotfiles to be able to have identical setups between my work and personal machines. My Visual Studio Code configuration is one piece of those. While there is an extension out there that does extension syncing, I didn't find them ideal for my use-case as it also did a settings sync.

Backup Extensions

Let's output our list of extensions to a file.

code --list-extensions > extensions.txt

The file content will be similar to the following:

donjayamanne.githistory
eamodio.gitlens
johnpapa.vscode-peacock
ms-azuretools.vscode-docker
yzhang.markdown-all-in-one

Restore Extensions

Once we have our file listing our extensions, we can restore our extensions.

cat extensions.txt | xargs -L 1 code --install-extension

This line performs the code --install-extension command for every line in your file.

Use with a Script

To make these commands easier to use, we can use a script that wraps the code command. The following script will add code save-ext and code install-ext as commands. Any other standard command will simply be passed through.

#!/usr/bin/env bash

if command -v code >/dev/null 2>&1; then
  code() {
    case "$1" in
    save-ext)
      echo "Saving code extensions..."
      code --list-extensions > ~/.dotfiles/vscode/extensions.txt
      ;;
    install-ext)
      echo "Installing code extensions..."
      cat ~/.dotfiles/vscode/extensions.txt | xargs -L 1 code --install-extension
      ;;
    *)
      command code "$@"
      ;;
    esac
  }
fi

To use this script, modify the extensions.txt file path and also add the script to your PATH.

  • code save-ext will output your extensions to file
  • code install-ext will install them from file

I'd recommend saving this file to your personal dotfiles to share between your dev environments. Here are mine.