linux - 每次执行 bash 脚本时执行不同的任务

标签 linux bash

假设我有 2 个任务。 是否可以编写一个 bash 脚本(一个脚本),当我们第一次运行脚本时执行第一个任务,第二次运行脚本时执行第二个任务,第三次运行脚本时执行第一个任务,第四次运行脚本时执行第二个脚本?

最佳答案

是的,通过记住/保留上次运行的内容很容易做到这一点。

$ echo "1" > current_counter
$ cat current_counter 
1
$ vim main.bash
$ cat main.bash 
#/bin/bash
current_counter=$(<"current_counter")
if [[ "$((${current_counter}%2))" -eq 1 ]]; then
    echo "Running task 1"
else
    echo "Running task 2"
fi
echo "$((${current_counter}+1))" > "current_counter"
$ bash main.bash 
Running task 1
$ cat current_counter 
2
$ bash main.bash 
Running task 2
$ cat current_counter 
3
$ bash main.bash 
Running task 1
$ cat current_counter 
4
$ bash main.bash 
Running task 2
$ cat current_counter 
5
$ 

您也可以在 current_counter 文件中使用 bool 值 0 或 1,或者只是检查文件是否存在,但它仅适用于这种情况。如果你有更多的任务(不仅仅是 2 个),比如 3 个甚至 100 个,上面的脚本很容易扩展;那么您只需更改模数并添加更多条件来处理每个残基。

关于linux - 每次执行 bash 脚本时执行不同的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958895/

相关文章:

python - 如何在python中的arraylist中存储变量

linux - 你将如何制作一个 shell 脚本来监控挂载和日志问题?

bash - 使用 docker 运行容器时出错

bash - 查找:缺少 -exec 的参数

无法更改 SIGINT 的默认操作

php - PHP 中的 FreeType 扩展

Linux shell 计算 key 的简单方法

bash - 处理带有数字部分的文件

git - 是否可以在没有 git clone 的情况下获取远程 git repo 的提交日志/消息

linux - 克服表现不佳的 Linux 进程?