如何在Bash中将目录文件移至父目录及修复GitHub Workflow异常
解决mdBook产物迁移到仓库根目录的GitHub Workflow问题
问题背景
要通过GitHub Workflow自动构建mdBook文档,mdBook会将构建产物生成到book目录。需求是把这些产物迁移到仓库根目录,再提交变更到指定的live分支,但操作时遇到以下问题:
- 执行
mv -f book .报错:mv: 'book' and './book' are the same file - 执行
mv -f book ..看似成功,但最终丢失所有文件 - 尝试
cp -r book .或cp -r book ..均未生效,且无法使用/或~作为目标路径
原Workflow代码如下:
name: Build on: push: branches: [ "master" ] pull_request: branches: [ "master" ] workflow_dispatch: inputs: logLevel: description: 'Log level' required: true default: 'warning' type: choice options: - info - warning - debug tags: description: 'Build' required: false type: boolean environment: description: 'Environment to run tests against' type: environment required: true permissions: contents: write env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install mdbook CLI run: cargo install mdbook --version ~0.4 - name: Build book run: mdbook build - name: Git commit report run: | mv -f book . rm -rf book # Git commit git config --global user.name '<username>' git config --global user.email '<e-mail>' git switch -C live git rm -r .github src theme .gitignore book.toml git add . git commit -m "Automated report" git push origin -f live
问题原因
原命令mv -f book .是试图将book目录移动到当前目录,而当前目录已经存在book目录,所以报错。而mv -f book ..是把book目录移到上级目录,但后续提交的是当前仓库目录,所以产物不会被包含进去。核心错误是没有将book目录内的内容迁移到根目录,而是错误地操作了book目录本身。
修复后的Workflow
修改Git commit report步骤,先切换到live分支,清理根目录无关文件,再将book内的所有内容(包括隐藏文件)迁移到根目录:
name: Build on: push: branches: [ "master" ] pull_request: branches: [ "master" ] workflow_dispatch: inputs: logLevel: description: 'Log level' required: true default: 'warning' type: choice options: - info - warning - debug tags: description: 'Build' required: false type: boolean environment: description: 'Environment to run tests against' type: environment required: true permissions: contents: write env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install mdbook CLI run: cargo install mdbook --version ~0.4 - name: Build book run: mdbook build - name: Git commit report run: | # 切换到live分支(不存在则创建) git switch -C live # 清理根目录不需要的文件/目录 git rm -r --ignore-unmatch .github src theme .gitignore book.toml # 开启匹配隐藏文件的选项,确保book内的隐藏文件也能被迁移 shopt -s dotglob # 将book目录下的所有内容移动到根目录 mv book/* . # 移除空的book目录 rm -rf book # Git提交配置 git config --global user.name '<username>' git config --global user.email '<e-mail>' git add . git commit -m "Automated report" git push origin -f live
关键修改说明
- 先切换分支再清理:避免在master分支直接修改内容,先切换到
live分支再清理无关文件,逻辑更清晰 - 迁移目录内内容而非目录本身:用
shopt -s dotglob开启隐藏文件匹配,再执行mv book/* .将book内的所有文件(包括隐藏文件)移动到根目录 - 移除空book目录:迁移完成后删除空的
book目录,避免提交无用目录
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

