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 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
}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 pathssh://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.
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/projectfrom afile://URI. - The third connects to the remote host
myhost. - The fourth opens a specific directory on
myhost.
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.