无法打破While循环

时间:2019-08-29 18:13:02

标签: bash loops if-statement while-loop do-while

当它到达文件中的空白行时,我想打破循环。问题是我的正则表达式用来对数据进行条件处理,因此用字符创建了一行,因此我从一开始就需要检查一下行是否为空,这样我就可以突破了。我想念什么?

#!/bin/bash

#NOTES: chmod this script with chmod 755 to run as regular local user

#This line allows for passing in a source file as an argument to the script (i.e: ./script.sh source_file.txt)
input_file="$1"

#This creates the folder structure used to mount the SMB Share and copy the assets over to the local machines
SOURCE_FILES_ROOT_DIR="${HOME}/operations/source" 
DESTINATION_FILES_ROOT_DIR="${HOME}/operations/copied_files"

#This creates the fileshare mount point and place to copy files over to on the local machine.
 echo "Creating initial folders..."
 mkdir -p "${SOURCE_FILES_ROOT_DIR}"
 mkdir -p "${DESTINATION_FILES_ROOT_DIR}"
 echo "Folders Created! Destination files will be copied to ${DESTINATION_FILES_ROOT_DIR}/SHARE_NAME"


while read -r line; 
  do  
    if [ -n "$line" ]; then 
        continue
    fi      
    line=${line/\\\\///}
    line=${line//\\//}
    line=${line%%\"*\"}
    SERVER_NAME=$(echo "$line" | cut -d / -f 4);
    SHARE_NAME=$(echo "$line" | cut -d / -f 5);
    ASSET_LOC=$(echo "$line" | cut -d / -f 6-);
    SMB_MOUNT_PATH="//$(whoami)@${SERVER_NAME}/${SHARE_NAME}";

     if df -h | grep -q "${SMB_MOUNT_PATH}"; then
       echo "${SHARE_NAME} is already mounted. Copying files..."
     else
       echo "Mounting it"
       mount_smbfs "${SMB_MOUNT_PATH}" "${SOURCE_FILES_ROOT_DIR}"
      fi
   cp -a ${SOURCE_FILES_ROOT_DIR}/${ASSET_LOC} ${DESTINATION_FILES_ROOT_DIR}

  done < $input_file

# cleanup
 hdiutil unmount ${SOURCE_FILES_ROOT_DIR}

exit 0

该脚本在到达空白行然后停止时将实现预期的结果。当我删除

时,脚本有效
if [ -n "$line" ]; then 
    continue
fi

该脚本运行并提取资产,但仍在继续运行且永不中断。当我按原样进行操作时,我会得到:

  

创建初始文件夹...
  文件夹已创建!目标文件将被复制到/ Users / baguiar / operations / copied_files
  安装
  mount_smbfs:服务器连接失败:主机没有路由
  hdiutil:卸载:由于错误16,无法卸载“ / Users / baguiar / operations / source”。
  hdiutil:卸载失败-资源繁忙

1 个答案:

答案 0 :(得分:2)

cat test.txt
  

这是一些文件
  里面有行

     

还有空行

     

while read -r line; do
  if [[ -n "$line" ]]; then
    continue
  fi
  echo "$line"
done < "test.txt"

将打印出

  

那是因为-n matches strings that are not null, i.e., non-empty

听起来您对continue的含义有误解。这并不意味着“继续执行此循环步骤”,而是意味着“继续执行循环的下一步步骤”,即转到while循环的顶部,然后从文件的下一行开始运行它。

现在,您的脚本说“一行一行,如果行不为空,则跳过其余的处理”。我认为您的目标实际上是“逐行进行,如果行为空,请跳过其余的处理”。这将通过if [[ -z "$line" ]]; then continue; fi

来实现

TL; DR 您正在跳过所有非空行。使用-z to check if your variable is empty代替-n