Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aont/175ba61b6dcf8e520f839888115b67e3 to your computer and use it in GitHub Desktop.

Select an option

Save aont/175ba61b6dcf8e520f839888115b67e3 to your computer and use it in GitHub Desktop.

A Handy Bash Function to Open Remote Folders in VS Code via SSH

When working with multiple servers, it’s often convenient to open remote folders directly in Visual Studio Code (VS Code). Instead of manually constructing VS Code’s --remote or --folder-uri arguments every time, you can define a simple Bash function to handle this automatically.

The Bash Function

The function below wraps the code command and maps different types of arguments into the proper VS Code format:

code() {

  if [[ $# -eq 0 ]]; then
    code_impl
    return
  fi

  mapped=()

  for arg in "$@"; do
    if [[ "$arg" == ssh://* ]]; then
      rest="${arg#ssh://}"            # host[/path...]
      if [[ "$rest" == */* ]]; then
        host="${rest%%/*}"
        path="/${rest#*/}"
        [[ "${path: -1}" == "/" ]] || path="${path}/"
        folder_uri="vscode-remote://ssh-remote+${host}${path}"
        mapped+=(--folder-uri "$folder_uri")
      else
        host="$rest"
        mapped+=(--remote "ssh-remote+${host}")
      fi
    elif [[ "$arg" == file://* ]]; then
      file="${arg#file://}"
      mapped+=("$file")
    else
      mapped+=("$arg")
    fi
  done

  code_impl "${mapped[@]}"
  return
}

How It Works

This wrapper converts different kinds of URIs into the correct form for VS Code:

  • Plain arguments → passed through as-is
  • file://... → converted into a local file path
  • ssh://host → mapped to --remote "ssh-remote+host"
  • ssh://host/path... → mapped to a full folder URI like --folder-uri "vscode-remote://ssh-remote+host/path.../"

This means you don’t have to remember the exact syntax of VS Code’s remote arguments.

Usage Examples

Here are some practical examples:

code-wrapper hoge
code-wrapper file:///home/me/project
code-wrapper ssh://myhost
code-wrapper ssh://myhost/path/to/dir
  • The first example opens a local folder hoge.
  • The second opens /home/me/project from a file:// URI.
  • The third connects to the remote host myhost.
  • The fourth opens a specific directory on myhost.

Why Use This?

This function saves time and reduces mistakes by letting you use simple, consistent URIs for both local and remote projects. Whether you’re working on your own machine or managing code on multiple servers, it makes the workflow smoother and more efficient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment