【问题标题】:while loop not working in shell script while running the script from crontab从 crontab 运行脚本时,while 循环在 shell 脚本中不起作用
【发布时间】:2015-12-21 22:03:15
【问题描述】:

我正在尝试使用 while 循环逐行读取文件,例如:

while read Line; do
     echo Inside outer loop
     while read Line2; do
          .....
          echo Inside inner loop
          .....
     done < /absolute path of file/filename2
done < /absolute path of file/filename

脚本在独立运行时工作正常。但是当它从 crontab 运行时,它不会进入循环内部。

请提出可能的原因。

【问题讨论】:

    标签: shell while-loop crontab


    【解决方案1】:

    第二个while循环正在读取所有输入(“文件名”的第一行除外)。您需要重定向到单独的文件描述符:

    while IFS= read -r -u3 Line; do
         echo Inside outer loop
         while IFS= read -r -u4 Line2; do
              .....
              echo Inside inner loop
              .....
         done 4< "/absolute path of file/filename2"
    done 3< "/absolute path of file/filename"
    
    • 使用IFS=read -r 确保从文件中逐字读取该行。
    • read -u33&lt; file 使用特定的 fd
    • 如果你的真实路径有空格,你需要引用文件名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多