保存 bash 歷史紀錄
您也可以使用掛載來跨工作階段/容器重建保存您的 bash
命令歷史紀錄。
首先,更新您的 Dockerfile
,以便每次在 bash
中使用命令時,歷史紀錄都會更新並儲存在我們將持久保存的位置。
如果您有根使用者,請使用以下內容更新您的 Dockerfile
RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \
&& echo "$SNIPPET" >> "/root/.bashrc"
如果您有非根使用者,請使用以下內容更新您的 Dockerfile
。將 user-name-goes-here
替換為容器中非根使用者的名稱。
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) 執行Dev Containers: Rebuild Container 以接收變更。否則,請執行 Dev Containers: Open Folder in Container... 以連線到容器。
注意: 如果您的主機執行 Linux (包括 Windows 上的 WSL),且其使用者的 UID 和 GID 與開發容器中使用者的 UID 和 GID 不符,則開發容器使用者的 UID 和 GID 將會更新為主機使用者的 UID 和 GID,而且您需要將相同的更新套用至磁碟區,方法是在 devcontainer.json 中新增以下內容。
```json
"postCreateCommand": {
"Fix Volume Permissions": "sudo chown -R $(whoami): /commandhistory"
}
```