简体   繁体   English

如何检查bash脚本中是否执行过该命令,不再执行该命令?

[英]How to check if the command was executed in bash script and do not execute this command again?

I don't want to source my.sh script every time before I start packer build command... because I always forget to do this.我不想在每次启动 packer build 命令之前都获取 my.sh 脚本...因为我总是忘记这样做。 These tasks are repeatable and it makes sense to create a shell script for that.这些任务是可重复的,为此创建一个 shell 脚本是有意义的。

Problem : If the command问题:如果命令

$source env.sh

was executed once, I don't want to execute this command again but continue with the others.已执行一次,我不想再次执行此命令,而是继续执行其他命令。 Is there any solution for that?有什么解决办法吗? My script:我的脚本:

#!/bin/bash
set -e
echo "Today is $(date)"
echo "--------------------"
sleep 1.5
echo "1. Pass env variables"
source env.sh
echo "2. Check the configuration of Packer template"
packer validate example.pkr.hcl
echo "3. Build the image"
#packer build example.pkr.hcl

Set an variable inside your script, then test for the presence of that variable at the top of the script.在脚本中设置一个变量,然后在脚本顶部测试该变量是否存在。 For example:例如:

#!/bin/bash

if [ "${ALREADY_LOADED}" -ne "YES" ]; then

...
# Put commands here
...

ALREADY_LOADED=YES
fi

If you want this to persist to child processes, then use an environment variable instead of a local one, by export ing it.如果您希望它持续到子进程,请使用环境变量而不是本地变量,方法是export But be aware: Some things are not inherited by child processes.但请注意:有些东西不会被子进程继承。 For example, if your script sets an array variable, the child will not be able to see the array.例如,如果您的脚本设置了一个数组变量,孩子将看不到该数组。 So you may want to leave some commands outside the if...then...fi clause.因此,您可能希望在if...then...fi子句之外保留一些命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM