Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
unixshell“;改为;仅使用while循环的命令_Shell_Unix - Fatal编程技术网

unixshell“;改为;仅使用while循环的命令

unixshell“;改为;仅使用while循环的命令,shell,unix,Shell,Unix,当我这么做的时候 date|cut -d' ' -f4|cut -d':' -f1|read time echo $time date|cut -d' ' -f4|cut -d':' -f1| while read time do echo $time done 输出为空 但当我这么做的时候 date|cut -d' ' -f4|cut -d':' -f1|read time echo $time date|cut -d' ' -f4|cut -d':' -f1| while r

当我这么做的时候

date|cut -d' ' -f4|cut -d':' -f1|read time
echo $time
date|cut -d' ' -f4|cut -d':' -f1|
while read time
do

    echo $time
done
输出为空

但当我这么做的时候

date|cut -d' ' -f4|cut -d':' -f1|read time
echo $time
date|cut -d' ' -f4|cut -d':' -f1|
while read time
do

    echo $time
done
我得到小时时间输出…只有一个输出

为什么会这样


谢谢

您似乎在寻找这样的东西:

while true
do
    time=$(date '+%H')
    echo $time
    sleep 0.1
done
笔记
  • 正如您所发现的,一次调用
    date
    只会产生一个日期。将它连接到
    while
    循环将无法说服它继续生产

  • 这不是从
    date
    提取内容的可靠方法:

    date|cut -d' ' -f4|cut -d':' -f1|read time
    
    根据月份的日期是一位数还是两位数,它给出了不同的结果。我认为,您正在寻找一个小时,这是简单地完成了:

    date '+%H'
    
    如果要将其捕获到shell变量中,请使用:

    time=$(date '+%H')
    
  • 问题中的
    while
    循环如果没有延迟,将占用大量CPU时间。我添加了一个
    sleep0.1
    来降低速度

为什么它只适用于while循环 这与环境变量和子shell有关。比较和对比以下两种版本。在下面的第一个版本中,输出为空:

$ date | cut -d' ' -f4 | cut -d':' -f1 | read time
$ echo $time

$
在此版本中,输出为非空(并打印月份的日期):

这里的问题是
读取时间
在子shell中运行。这意味着在子shell结束时,环境变量的任何设置都将丢失。在后一个版本中有输出,因为
echo$time
语句在与
readtime
相同的子shell中运行

使用重定向和进程替换的替代方法 CharlesDuffy指出了另一种方法:

$ read time < <(date '+%H')
$ echo $time
21

这是你真正想要做的还是仅仅是一个例子?如果您只需要这样做,请尝试
time=$(date | cut-d'-f4 | cut-d':'-f1)
这个问题在BashFAQ 24(“我为什么不能用管道读取数据?”):…您可以运行
读取时间<…尽管只告诉
date
给您想要的东西会更有效,与使用其他程序提取内容不同:
time=$(date'+%H')
只需一个小时就可以了,最新版本的bash:
printf-v time%%(%H)T'
——没有子shell,因此开销更小。谢谢。。。。但我并不是真的想提取任何东西,我只想让date运行一次。。。。只是想知道为什么读取时间会失败,但添加while会让它失败work@demalegabi好啊这是因为,当在子shell中设置环境变量时,其值在子shell结束时丢失。我用一些相关信息更新了答案。值得注意或建议使用
read<@charlesduff<@Good idea。我在答案上加了这个。