Skip to content

Instantly share code, notes, and snippets.

@awesomebytes
Last active March 26, 2024 09:54
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save awesomebytes/8494fb216c42bc4a2fcaef6b4937a07e to your computer and use it in GitHub Desktop.
Save awesomebytes/8494fb216c42bc4a2fcaef6b4937a07e to your computer and use it in GitHub Desktop.
How to open Visual Studio Code via command line (local file, remote-ssh, docker, remote-docker)

How to open Visual Studio Code via command line

In order to open a Visual Studio Code sometimes we want to do it from the command line. Either because that allows us to just open the current file or folder, or because we would like to script opening some specific resource. This resource may be placed in another machine (e.g. via ssh), or in a docker container (running in the same machine or in another machine).

Local file or folder

code <file or folder>
# e.g. code .

Remote-ssh

Thanks to this thread. Note that you need the Remote - SSH extension installed.

# With 192.168.1.100 being the IP of the machine with the folder to open
code --folder-uri "vscode-remote://ssh-remote+192.168.1.100/home/myuser/myfolder/"

Docker container

Note that you need the Remote - Containers extension installed. Note that I found the attached-container+ code by starting Visual Studio Code with --verbose and looking at the output when I connected manually.

# Encode the following config in HEX with your container name (test here):
# {"containerName":"/$CONTAINER_NAME"}
printf {\"containerName\":\"/test\"} | od -A n -t x1 | tr -d '[\n\t ]'
# Outputs for me 7b22636f6e7461696e65724e616d65223a222f74657374227d
code --folder-uri "vscode-remote://attached-container+7b22636f6e7461696e65724e616d65223a222f74657374227d/home/user/myproject"

# In a scriptable manner
CONTAINER_NAME=vigorous_mestorf
FOLDER=/home/dockeruser/myfolder
HEX_CONFIG=$(printf {\"containerName\":\"/$CONTAINER_NAME\"} | od -A n -t x1 | tr -d '[\n\t ]')
code --folder-uri "vscode-remote://attached-container+$HEX_CONFIG$FOLDER"

Remote docker container

Note that you need the Remote - Containers extension installed. You may also need your SSH key to be installed (ssh-add-key -i ~/.ssh/id_rsa user@192.168.1.100) in the target machine.

# With 192.168.1.100 being the IP of the machine with the docker container running
export DOCKER_HOST="ssh://user@192.168.1.100"
CONTAINER_NAME=zen_gates
FOLDER=/home/dockeruser/myfolder
HEX_CONFIG=$(printf {\"containerName\":\"/$CONTAINER_NAME\"} | od -A n -t x1 | tr -d '[\n\t ]')
code --folder-uri "vscode-remote://attached-container+$HEX_CONFIG$FOLDER"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment