【问题标题】:I cannot seem to run this properly... It stucks and does not display an output我似乎无法正常运行...它卡住并且不显示输出
【发布时间】:2012-09-30 02:02:55
【问题描述】:

这是我的脚本:

while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f | xargs grep -l $startDate | xargs grep -l $startTime)
fordestination=`cut -d$ -f2 $thisfile | xargs cut -d ~ -f4`

echo $fordestination

startTime=$(( $startTime + 1 ))

done

【问题讨论】:

  • 它获取用户的日期和时间输入,然后在匹配这些输入和输出 $fordestination..

标签: performance bash loops while-loop


【解决方案1】:

我认为您的 cut 和 grep 命令可能会卡住。您可能应该确保它们的参数不为空,方法是使用[ -n "$string" ] 命令查看$string 是否不为空。在您的情况下,如果它是空的,它不会将任何文件添加到随后将使用它的命令中,这意味着该命令可能会等待来自命令行的输入(例如:如果 $string 为空而您这样做grep regex $string,grep 不会接收来自$string 的输入文件,而是等待来自命令行的输入)。这是一个“复杂”的版本,试图显示哪里可能出错:

while [[ $startTime -le $endTime ]]
do

thisfile=$(find * -type f)
if [ -n "$thisfile" ]; then
    thisfile=$(grep -l $startDate $thisfile)
    if [ -n "$thisfile" ]; then
        thisfile=$(grep -l $startTime $thisfile)
        if [ -n "$thisfile" ]; then
            thisfile=`cut -d$ -f2 $thisfile`

            if [ -n "$thisfile" ]; then
                forDestination=`cut -d ~ -f4 $thisfile`
                echo $fordestination
            fi
        fi
    fi
fi

startTime=$(( $startTime + 1 ))

done

这是一个更简单的版本:

while [[ $startTime -le $endTime ]]
do

thisfile=$(grep -Rl $startDate *)
[ -n "$thisfile" ] && thisfile=$(grep -l $startTime $thisfile)

[ -n "$thisfile" ] && thisfile=`cut -d$ -f2 $thisfile`
[ -n "$thisfile" ] && cut -d ~ -f4 $thisfile

startTime=$(( $startTime + 1 ))

done

“-R”告诉 grep 递归搜索文件,&& 告诉 bash 如果前面的命令成功,则只执行它后面的命令,而 && 前面的命令是测试命令(用于ifs)。

希望这会有所帮助 =)

【讨论】:

  • 请问printf "%s\\n" 有什么用?
  • 当然。很抱歉编辑过多,我误解了你想要做什么,所以printf 的第一个版本有点不正确。 printf 命令类似于 C 中的 printf 函数。它用于代替 echo "$bla",因为如果 $bla 以连字符 (-) 开头,echo 将被解释为一个选项,而不是字符串打印。这就是为什么当您要打印的字符串以变量开头时使用printf %s//n "$bla" 会更安全。
猜你喜欢
  • 1970-01-01
  • 2022-11-11
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2016-05-25
  • 1970-01-01
相关资源
最近更新 更多