bash - 在 bash 中创建将运行特定时间的 while 循环

标签 bash shell loops datetime

我有兴趣在 上运行的 bash (版本:3.2.57(1)-release) 中创建 while 循环它将运行特定的秒数/分钟数。

示例

例如,我想创建 n 个文件,每个文件都包含 5 秒期间的当前日期和时间。

方法

我的循环结构相当基本:

i=$cmd(date %ss)
j=$i + 10
while [ $i -lt $j ]
do
fileName=$cmd(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32)
date > $fileName
i=date %ss
done

问题

当我尝试执行脚本时,出现以下错误:

loop.sh: line 1: syntax error near unexpected token `('
loop.sh: line 1: `i=$cmd(date %ss)'

期望的结果:

  • i 计数器反射(reflect)秒数,循环在 10 秒后停止
  • 在当前工作目录中创建以当前日期为唯一内容的随机 *.txt 文件

最佳答案

以下内容将产生您在“所需结果”中所述的内容。

#!/bin/bash

i="$(date +%s)"
j="$(( i + 10 ))"

while [ $i -lt $j ]; do
    fileName="$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32)"
    date > "${fileName}.txt"
    i="$(date +%s)"
done

关于bash - 在 bash 中创建将运行特定时间的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955144/

相关文章:

java - 需要解释以下java代码的输出

python - python 是否在循环中的迭代结束时进行垃圾收集?

linux - Bash:从 ./将所有目录的内容移动到各自的 ../

linux - 一个用于计算按键排序的字段的平均值的单行?

python - 通过 C++ 调用系统不一致失败

string - 如果变量名存储为字符串,如何获取变量值?

linux - Shell 脚本 - 根据文件创建时间查找命令输出排序

c - 自动在线法官拒绝我的数学难题解决方案

Bash 的最后一个索引

linux - 如何让bash shell输出带有颜色的字体?