无法突破 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: 卸载: "/Users/baguiar/operations/source" 由于错误 16,卸载失败。
hdiutil:卸载失败 - 资源繁忙

cat test.txt

这是一些文件
里面有行

和空行

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

将打印出来

这是因为-n匹配非空字符串,即非空字符串。

听起来你对continue的意思有误解。它并不意味着"继续循环的这一步",而是意味着"继续循环的下一步",即转到while循环的顶部并从文件中的下一行开始运行它。

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

来实现TL;DR您跳过了所有非空行。使用-z检查变量是否为空而不是-n

最新更新