現已釋出!閱讀關於 11 月新增功能和修復的內容。

持久化 Bash 歷史記錄

您也可以使用掛載來在會話/容器重建之間保留 bash 命令歷史記錄。

首先,更新您的 Dockerfile,以便每次在 bash 中使用命令時,歷史記錄都會更新並存儲在一個我們將保留的位置。

如果您有 root 使用者,請使用以下內容更新您的 Dockerfile

RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \
    && echo "$SNIPPET" >> "/root/.bashrc"

如果您有非 root 使用者,請使用以下內容更新您的 Dockerfile。將 user-name-goes-here 替換為容器中 非 root 使用者 的名稱。

ARG USERNAME=user-name-goes-here

RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \
    && mkdir /commandhistory \
    && touch /commandhistory/.bash_history \
    && chown -R $USERNAME /commandhistory \
    && echo "$SNIPPET" >> "/home/$USERNAME/.bashrc"

接下來,新增一個本地捲來儲存命令歷史記錄。此步驟因您是否使用 Docker Compose 而異。

  • Dockerfile 或映象:在 devcontainer.json 檔案中使用 mounts 屬性(VS Code 1.41+)。

      "mounts": [
          "source=projectname-bashhistory,target=/commandhistory,type=volume"
      ]
    
  • Docker Compose:使用以下內容更新(或 擴充套件)您的 docker-compose.yml 以適應相應的服務。

    version: '3'
    services:
      your-service-name-here:
        volumes:
          - projectname-bashhistory:/commandhistory
         # ...
    volumes:
      projectname-bashhistory:
    

最後,如果您已經構建了容器並連線到它,請從命令面板(F1)執行 開發容器:重建容器 以獲取更改。否則執行 開發容器:在容器中開啟資料夾... 連線到容器。

注意:如果您的主機正在執行 Linux(包括 Windows 上的 WSL)並且其使用者的 UID 和 GID 與開發容器中使用者的 UID 和 GID 不匹配,則開發容器使用者的 UID 和 GID 將更新為與主機使用者相同,並且您需要透過在 devcontainer.json 中新增以下內容來對卷應用相同的更新。

```json
  "postCreateCommand": {
    "Fix Volume Permissions": "sudo chown -R $(whoami): /commandhistory"
  }
```

影片:如何在開發容器中保留 bash 歷史記錄

© . This site is unofficial and not affiliated with Microsoft.