当循环到达文件中的空行时,我想要断开循环。问题是,我的regexp习惯于为我的数据设定条件,用字符创建一行,所以从一开始就需要一些东西来检查一行是否为空,这样我就可以跳出。我遗漏了什么?
#!/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:卸载失败-资源繁忙
发布于 2019-08-29 18:20:46
cat test.txt这是一些文件 里面有线 空空如也 等
while read -r line; do
if [[ -n "$line" ]]; then
continue
fi
echo "$line"
done < "test.txt"会打印出来
那是因为 matches strings that are not null, i.e., non-empty。
听起来你好像误解了continue的意思。它的意思不是“在循环的这一步中继续”,而是“继续到循环的下一步”,即转到while循环的顶部,从文件中的下一行开始运行它。
现在,您的脚本写着“逐行走,如果该行不是空的,跳过其余的处理”。我认为你的目标实际上是“一行行,如果行是空的,跳过其余的处理”。这将由if [[ -z "$line" ]]; then continue; fi实现
TL;博士,您跳过了所有非空行。使用 to check if your variable is empty而不是-n。
https://stackoverflow.com/questions/57715761
复制相似问题