shell如何制作第一个输入的副本

时间:2019-02-13 02:50:01

标签: shell sh

我有一个接受输入的脚本,我再次调用了该脚本,但我想从第一次运行中保存输入变量,并让条件在我的第二个条件下失败,因此它不会在运行时再次运行该脚本。第二轮。

这是我运行脚本的方式:

./scripts/my_script.sh my_input

my_script.sh:

#!/bin/sh

INPUT=$1

COPY_OF_FIRST_RAN_INPUT = INPUT # this won't work cause on the second run it will get replace

if [ some_condtion is true ] && [ COPY_OF_FIRST_RAN_INPUT = $1 ]; then 
    ./scripts/build-image.sh $SECOND_RAN_INPUT; else 
fi

我希望第二个条件失败,因为我不想再次运行脚本。我只希望脚本运行一次。有没有一种方法可以存储第一个输入,因此当第二遍输入将失败$SECOND_RAN_INPUT = $COPY_OF_FIRST_RAN_INPUT条件并且不会进入第二遍if来再次运行脚本时?

1 个答案:

答案 0 :(得分:3)

如果您希望在调用之间持续存在,请使用文件系统。

这看起来像:

#!/bin/bash
input=$1

if [[ -e "$HOME/.last-invocation" ]]; then
  # this branch runs when there has been a prior invocation
  # here, we read the last invocation's input into the variable named last_input
  IFS= read -r -d '' last_input <"$HOME/.last-invocation"
  # here, we do something with both prior and current inputs.
  do-something-with "$last_input" "$input"
fi

# this branch runs whether or not there has been a prior invocation
# here, we save our current input to file as a NUL-terminated string.
printf '%s\0' "$input" >"$HOME/.last-invocation"