我在 bash 中運行它,即使有一個 .txt 檔案,它也會在終端中列印出“沒有要創建的新檔案夾”。我錯過了什么嗎?
FILES=cluster-02/*/*
for f in $FILES
do
if [[ $f == *."txt" ]]
then
cat $f | xargs mkdir -p
else
echo "No new folders to create"
fi
done;
uj5u.com熱心網友回復:
您正在回圈多個檔案,因此第一個結果可能會觸發 ,if而第二個結果可能會顯示else.
您可以將通配符結果保存在一個陣列中,檢查其中是否有內容,如果有則回圈:
shopt -s nullglob
FILES=( foo/* )
if (( ${#FILES[@]} )); then
for f in "${FILES[@]}"; do
if [[ $f == *."txt" ]]; then
echo $f
fi
done
else
echo "No new folders to create"
fi
uj5u.com熱心網友回復:
正如第一條評論中提到的,行為確實與您對腳本的期望一樣:您運行所有檔案、文本檔案和其他檔案。如果您的檔案是文本檔案,則執行if-case;如果您的檔案是另一種型別的檔案,則執行else-case。
為了解決這個問題,您可能決定不考慮其他檔案(僅處理文本檔案),我認為您可以這樣做:
FILES=cluster-02/*/*.txt
uj5u.com熱心網友回復:
#!/usr/bin/env bash
# Create an array containing a list of files
# This is safer to avoid issues with files having special characters such
# as spaces, glob-characters, or other characters that might be cumbersome
# Note: if no files are found, the array contains a single element with the
# string "cluster-02/*/*"
file_list=( cluster-02/*/* )
# loop over the content of the file list
# ensure to quote the list to avoid the same pitfalls as above
for _file in "${file_list[@]}"
do
[ "${_file%.txt}" == "${_file}" ] && continue # skip, not a txt
[ -f "${_file}" ] || continue # check if the file exists
[ -r "${_file}" ] || continue # check if the file is readable
[ -s "${_file}" ] || continue # check if the file is empty
< "${_file}" xargs mkdir -p -- # add -- to avoid issues with entries starting with -
_c=1
done;
[ "${_c}" ] || echo "No new folders to create"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460382.html
