将函数调用分配给变量时终止 bash 脚本

问题描述

我有以下代码来演示:

<?PHP

namespace Database\Factories;

use App\Models\Debtor;
use Illuminate\Database\Eloquent\Factories\Factory;

class DebtorFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Debtor::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function deFinition()
    {
        return [
            'created_at' => Now(),'created_by_id' => '3','rechtsform' => 'Unternehmen','name' => $this->faker->company    
        ];
    }
}

你可以看到如果我运行这个脚本,它会打印出以下输出

#!/bin/bash
function demo() {

   echo "This is A"
   exit 1
   echo "This is B"
}


input=$(demo)
echo "${input}"
echo "This is C"

由于我有 This is A This is C 函数,脚本没有终止并打印最后一条语句 exit 1

但是当我这样调用函数时:

This is C

然后程序终止了,并没有打印最后一条语句“This is C”。输出为:

#!/bin/bash
function demo() {

   echo "This is A"
   exit 1
   echo "This is B"
}


demo
echo "${input}"
echo "This is C"

对此是否有解释,以及如何在有 This is A 时强制脚本终止,以及将函数分配给给定示例的变量。这意味着,在 exit 1

之后不应打印其他语句

解决方法

赋值时可以查看退出状态,失败退出主脚本。

input=$(demo) || exit 1