cd 到一个目录并执行许多命令

Dil*_*war 10 bash

我有以下脚本。

#!/bin/bash
mount /dev/sda6 /mnt/gentoo
set +e
cd /mnt/gentoo && mount -t proc none /mnt/gentoo/proc \
 && mount --rbind /dev /mnt/gentoo/dev \
 && mount --rbind /sys /mnt/gentoo/sys \
 && chroot /mnt/gentoo /bin/bash \
 && source /etc/profile  \
 && export PS1="(chroot)$PS1" 
Run Code Online (Sandbox Code Playgroud)

我在这里试图完成的是切换到一个目录/mnt/gentoo并执行几个命令。当没有安装任何路径时,这第一次工作正常。但是如果我在某些路径上成功执行安装后运行它,它不会继续并在第一次失败时停止。即使由于“已安装”错误而导致安装失败,我也希望执行所有命令。我怎样才能做到这一点?

还有比将所有这些命令组合在一行中更好的方法吗?

Gil*_*il' 8

使用&&命令之间的运算符,每个命令按顺序运行,如果任何命令失败(即返回非零状态),则不执行后续命令。

如果您无论如何都想继续前进,请使用;(或换行符,等效的)而不是&&. 在这里,你需要执行一个命令,如果成功,再执行一些命令,不管成功与否。实现此目的的一种方法是将这些命令放在一个大括号组中(只是cd … && mount1; mount2不起作用,因为mount2无论是否cd由于优先级,它都会执行)。

cd /mnt/gentoo && {
  mount -t proc none /mnt/gentoo/proc
  mount --rbind /dev /mnt/gentoo/dev
  mount --rbind /sys /mnt/gentoo/sys
  …
}
Run Code Online (Sandbox Code Playgroud)

或者,如果cd失败,退出脚本或从函数返回。

cd /mnt/gentoo || exit $?
mount -t proc none /mnt/gentoo/proc
…
Run Code Online (Sandbox Code Playgroud)

或者,在set -e,下运行,并|| true在可能失败的命令之后放置(“或继续执行”)。

set -e
cd /mnt/gentoo
mount -t proc none /mnt/gentoo/proc || true
…
Run Code Online (Sandbox Code Playgroud)

或者,编写一个必须成功的命令:测试是否/proc已经安装等等。

mount_if_needed () {
  eval "mount_point=${\$#}"
  awk -v target="$mount_point" '$2 == target {exit(0)} END {exit(1)}' </proc/mounts ||
  mount "$@"
}
set -e
cd /mnt/gentoo
mount_if_needed -t proc none /mnt/gentoo/proc
Run Code Online (Sandbox Code Playgroud)

您在调用chroot. 你写过:“在 chroot 中运行 bash。当 bash 退出时,运行sourceexport。” 这可能不是你的意思。/etc/profile可以通过使 bash 成为登录 shell 来完成阅读。一种可能的设置方法PS1可能是在运行 bash 之前设置它,但如果/etc/profile覆盖它,这将不起作用,这很常见。更好的方法是设置PS1in ~/.bashrc if 在 chroot ( .bashrc, not.profile ) 中运行。

chroot . bash --login
Run Code Online (Sandbox Code Playgroud)

Debian使用下面的代码来设置PS1/etc/bash.bashrc基础上的内容/etc/debian_chroot

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
Run Code Online (Sandbox Code Playgroud)

或者,对于提示,请改用环境变量:运行

CHROOT_LOCATION=$PWD chroot bash --login
Run Code Online (Sandbox Code Playgroud)

并将其放入~/.bashrcor 中/etc/bash.bashrc

if [ -n "$CHROOT_LOCATION" ]; then PS1="($CHROOT_LOCATION)$PS1"; fi
Run Code Online (Sandbox Code Playgroud)


Flu*_*lup 6

&&在这种情况下,分隔符表示“仅当最后一个命令成功时才继续”。如果您;改为使用,则无论结果如何,命令都会按顺序执行。

请注意,如果这是一项 cron 作业或其他对写入 stderr 的内容敏感的内容,则需要将错误重定向到/dev/null.