LoginSignup
15
8

More than 1 year has passed since last update.

codeコマンドでVisual Studio Codeを起動と同時にSSHリモート接続する方法

Last updated at Posted at 2020-05-08

結論

コメントをいただいた @kerikun11 の素敵なzshファンクションで解決です!

以下は経緯です。ご参考まで。

codeコマンドでリモートディレクトリを開きたい

Visual Studio CodeでSSHリモート開発する機会が増えてきました。

codeコマンドでVisual Studio Codeを起動して、同時に指定ホストにSSH接続、ディレクトリまで開く方法がきっとある!…と信じつつも上手く見つけられず手間を感じていましたが、やっと発見。

--folder-uriオプションを使い、こんな感じに指定するようです。

code --folder-uri "vscode-remote://ssh-remote+<hostname>/<path>"

普段遣いには冗長なので、こんな感じのスクリプトを作りました。

/usr/local/bin/sshcode
#!/bin/bash

# 引数(ホスト:ディレクトリ)は必須
location="$1"
if [ "$location" = "" ]; then
  echo "usage: $0 <host:path>"
  exit 1
fi

# ホストとディレクトリに分割(ディレクトリ部がない場合は引数=ホストとみなす)
host=${location%%:*}
dir=${location##*:}
if [ "$host" = "$dir" ]; then
  dir=""
fi

# ディレクトリ部が空または/で始まらない場合はホームディレクトリを取得
home=""
if [ "$dir" = "" -o "${dir:0:1}" != "/" ]; then
  home="$(ssh $host pwd)/"
fi

# vscodeでSSH直接接続
path="$home$dir"
code --folder-uri "vscode-remote://ssh-remote+$host$path"

こんな感じでVisual StudioによるSSHリモート開発がとっても楽に!

sshcode foo # ホストfooのホームディレクトリにリモート接続接続
sshcode bar@foo # barユーザーとしてホストfooのホームディレクトリにリモート接続
sshcode foo:project # ホストfooのホームディレクトリにあるprojectディレクトリにリモート接続
sshcode foo:/app # ホストfooの/appにリモート接続

host:port記法は非対応です(自分が特に困らないので…)。

Help! zshタブ補完機能

引数をhost:pathにしたのは、ついでにscpのシェル補完を流用してパスを探しやすくしたかったのですが、私の技能では短時間で作れず断念…

zshでのいい感じの補完を実装する方法を教えて下さい!

15
8
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8