0%

vscode 连接 ssh linux 服务器 使用 code 打开文件

背景

在本机环境下, 可以在命令行直接使用 code 快捷打开对应文件夹. 但是在 ssh 的情况下, 该命令默认无效. 手动选择文件夹再打开又太慢了.
其实在 SSH 服务器的家目录下有一个 .vscode-server 文件夹,找到里面的 code 可执行文件,并将它添加到环境变量中即可。

自动加载脚本

  • 因为 vscode-server 会自动更新, code 路径会变. 所以这里采取读取 code 的版本文件后手动拼接具体路径
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    load_remote_code() {
    local lru_file="$HOME/.vscode-server/cli/servers/lru.json"

    if [ ! -f "$lru_file" ]; then
    echo "LRU file not found: $lru_file"
    return 1
    fi

    if ! command -v jq >/dev/null 2>&1; then
    echo "jq is required but not installed."
    return 1
    fi

    # 读取最近使用的 server 目录
    local server_dir
    server_dir=$(jq -r '.[0]' "$lru_file")

    if [ -z "$server_dir" ] || [ "$server_dir" = "null" ]; then
    echo "Failed to parse server directory from $lru_file"
    return 1
    fi

    # 拼出 code 的路径
    local code_path="$HOME/.vscode-server/cli/servers/$server_dir/server/bin/remote-cli"

    if [ ! -d "$code_path" ]; then
    echo "Remote CLI directory not found: $code_path"
    return 1
    fi

    # ---- 避免重复添加到 PATH ----
    case ":$PATH:" in
    *":$code_path:"*)
    echo "PATH already contains: $code_path"
    ;;
    *)
    export PATH="$code_path:$PATH"
    echo "Added to PATH: $code_path"
    ;;
    esac

    echo "Loaded VS Code remote CLI:"
    echo " Server: $server_dir"
    echo " CLI path: $code_path"
    echo "code command resolved to: $(command -v code)"
    }

    # 有的时候提示挺有用的, 但是被自动加载情况下会有警告. 简单屏蔽下
    load_remote_code >/dev/null
-------------本文结束再接再厉-------------

本文标题:vscode 连接 ssh linux 服务器 使用 code 打开文件

文章作者:IITII

发布时间:2025年08月27日 - 10:08

最后更新:2026年02月27日 - 10:02

原始链接:https://iitii.github.io/2025/08/27/1/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。