[英]Unable to break out of While loop
當文件中出現空白行時,我想打破循環。 問題是我的正則表達式用來對數據進行條件處理,因此用字符創建了一行,因此我從一開始就需要檢查一下行是否為空,這樣我就可以突破了。 我想念什么?
#!/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:卸載失敗-資源繁忙
cat test.txt
這是一些文件
里面有線和空行
等等
while read -r line; do
if [[ -n "$line" ]]; then
continue
fi
echo "$line"
done < "test.txt"
將打印出來
這是因為-n
匹配不為null的字符串,即non-empty 。
聽起來您對continue
意味着什么有誤解。 這並不意味着“在循環的此步驟中繼續”,而是“繼續至循環的下一個步驟”,即轉到while
循環的頂部並從文件的下一行開始運行它。
現在,您的腳本說“一行一行,如果行不為空,請跳過其余的處理”。 我認為您的目標實際上是“逐行進行,如果行為空,請跳過其余的處理”。 if [[ -z "$line" ]]; then continue; fi
可以實現if [[ -z "$line" ]]; then continue; fi
if [[ -z "$line" ]]; then continue; fi
TL; DR您將跳過所有非空行。 使用-z
檢查變量是否為空,而不是-n
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.