首页 > 解决方案 > 在 bash 中创建“首次运行”通知?

问题描述

在 bash 脚本中发出“首次运行”通知的最佳方法是什么?我试着export FIRSTRUN="no"先放,然后放

`if [ -z "$FIRSTRUN" ]; then
echo "It seems that this may be your first time running this script.";
echo "Please ${GREEN}test whether the needed components are installed${RESET}.";
echo "";
fi`

但它只是在每次运行脚本时执行。如果我将ifexport FIRSTRUN="no"部分放在后面,它永远不会运行代码的if部分。所以这行不通。 我是新手,所以请帮忙:D

标签: bash

解决方案


您无法从脚本中修改父 shell 状态,因此尝试导出变量将不起作用。

您可以使用配置文件来存储一个变量,该变量确定脚本是否已经运行:

#!/bin/bash

# load vars from config at the start of the script
if [[ -f ~/.your_script.conf ]]; then
  . ~/.your_script.conf
fi

# check whether var has been set to determine first run
if [[ -z $has_run ]]; then
  echo 'first run'

  # set variable in config file for next time
  echo 'has_run=1' >> ~/.your_script.conf
fi

或者,如果这是您拥有的唯一“配置”,您可以在第一次运行后创建一个文件并检查其是否存在以确定脚本是否已运行。


推荐阅读