如果在bash中调用函数后语句未执行

时间:2019-04-03 15:22:03

标签: linux bash docker

我有一个bash脚本,如下所示:

#!/usr/bin/env bash
set -x

function run_container {
    CONTAINER_NAME=$(date +%s | sha256sum | base64 | head -c 16)
    echo "running: docker run -i --name $CONTAINER_NAME $REGISTRY/${1}"
    docker run -i --name $CONTAINER_NAME $REGISTRY"/"${1}
    echo "removing: container $CONTAINER_NAME from ${1}"
    docker container rm $CONTAINER_NAME
    echo "removing:  image $1"
    docker image rm ${REGISTRY}"/"${1}
    echo -e "\nDone with container ${1}\n\n\n"
    return 0
}


GCC_BUILD=${1}
GLIBC_BUILD=${2}
KERNEL_BUILD=${3}
POSTGRESQL_BUILD=${4}
PYTHON_BUILD=${5}
REINSTALL_PACKAGES=${6}
RUBY_BUILD=${7}
SEGMENTED_DOWNLOAD=${8}
UBUNTU_RSYNC=${9}


echo $GCC_BUILD
echo $GLIBC_BUILD
echo $KERNEL_BUILD
echo $POSTGRESQL_BUILD
echo $PYTHON_BUILD
echo $REINSTALL_PACKAGES
echo $RUBY_BUILD
echo $SEGMENTED_DOWNLOAD
echo $UBUNTU_RSYNC

REGISTRY="myregistry.com"


if [[ "$GCC_BUILD" == "true" ]]; then
    echo "Running GCC_BUILD"
    run_container "gcc-build"
fi

if [[ "$GLIBC_BUILD" == "true" ]]; then
    echo "Running GLIBC_BUILD"
    run_container "glibc-build"
fi

if [[ "$KERNEL_BUILD" == "true" ]]; then
    echo "Running KERNEL_BUILD"
    run_container "kernel-build"
fi

if [[ "$POSTGRESQL_BUILD" == "true" ]]; then
    echo "Running POSTGRESQL_BUILD"
    run_container "postgresql-build"
fi

if [[ "$PYTHON_BUILD" == "true" ]]; then
    echo "Running PYTHON_BUILD"
    run_container "python-build"
fi

if [[ "$REINSTALL_PACKAGES" == "true" ]]; then
    echo "Running REINSTALL_PACKAGES"
    run_container "reinstall-packages"
fi

if [[ "$RUBY_BUILD" == "true" ]]; then
    echo "Running RUBY_BUILD"
    run_container "ruby-build"
fi

if [[ "$SEGMENTED_DOWNLOAD" == "true" ]]; then
    echo "Running SEGMENTED_DOWNLOAD"
    run_container segmented-download
fi

if [[ "$UBUNTU_RSYNC" == "true" ]]; then
    echo "Running UBUNTU_RSYNC"
    run_container "ubuntu-rsync"
fi

echo "Finished build suite."

一旦if语句匹配,函数就会执行,但脚本会结束。因此,例如,如果GCC_BUILDGLIBC_BUILD变量为true,则脚本将为run_container执行GCC_BUILD函数中的操作,但不执行{{1} }。

如果我删除了GLIBC_BUILD语句中的run_container调用,而只是将if留在了那里,一切将按预期运行。

有关使脚本退出的功能的某些信息吗?

更新

由于我上面有echo,因此将打印出用于跟踪的内容:

set -x

由于有很多输出,所以我无法发布所有输出,但这是从xtrace打印的行

1 个答案:

答案 0 :(得分:1)

如果脚本(例如sshffmpegdocker run -i)可以读取stdin或修改终端配置之后,脚本意外停止执行,则需要执行一个步骤调试中是从/dev/null重定向该程序的标准输入。

要这样做(并解决名称在过程中带有空格的一些问题),请更改:

docker run -i --name $CONTAINER_NAME $REGISTRY"/"${1}

收件人:

docker run -i --name "$CONTAINER_NAME" "$REGISTRY/$1" </dev/null

...或者,如果需要更彻底地将命令与终端隔离,则可以(以某种效率为代价)为其指定非TTY stdout和stderr:

docker run -i --name "$CONTAINER_NAME" "$REGISTRY/$1" </dev/null > >(cat) 2>&1

...尽管我通常会先删除-i,再走那么远。