我正在嘗試使用 for 回圈迭代目錄中的所有檔案:
#!/bin/bash
myname="bandit24"
cd /var/spool/$myname
echo "Executing and deleting all scripts in /var/spool/$myname:"
for file in /var/spool/bandit24/*; # <----- here
do
if [ "$file" != "." -a "$file" != ".." ];
then
echo "Handling $file"
owner="$(stat --format "%U" ./$file)"
if [ "${owner}" = "bandit24" ]; then
timeout -s 9 60 ./$file
fi
rm -f ./$file
fi
done
但結果我得到以下資訊:
Executing and deleting all scripts in /var/spool/bandit24:
Handling /var/spool/bandit24/*
stat: cannot stat './/var/spool/bandit24/*': No such file or directory
該程式不嘗試迭代目錄中的/var/spool/bandit24/檔案,而是嘗試迭代/var/spool/bandit24/*檔案本身。但我想迭代目錄中的/var/spool/bandit24/檔案。怎么做?
附加問題
什么cd /var/spool/$myname意思(5行)?據我了解,它用于指定我們要作業的目錄,對嗎?
uj5u.com熱心網友回復:
for回圈基本上是健全的。但是,如果目錄為空,則回圈將執行一次,變數file包含文字 text /var/spool/bandit24/*。
該stat訊息不是來自for-loop,而是來自回圈中的命令之一。
正確的方法是在繼續之前測驗目錄是否為空。你可以把類似的東西
if [ $(find . -type f | wc -l) -eq 0 ] ; then
echo "Nothing to do"
exit 0
fi
就在cd.
對您的腳本的其他一些評論。
- 如果您
cd在腳本中執行 a ,則無需再指定完整路徑。 - 您的報價并不一致。
timeout -s 9 60 "./$file"如果您的檔案名從不包含空格或奇怪的字符,那可能不是問題,但我會,例如rm -f "./file" /var/spool/bandit/*永遠不會包含.or..,因此該測驗是無用的。- 您也可以將測驗替換為
if [ -f "$file" ] ; then
uj5u.com熱心網友回復:
我的Github存盤庫中有一個 bash 腳本,它遍歷指定目錄中的所有檔案。您可以指定搜索的深度,就像這樣。
mapfile files <<< "$(find "$f" -maxdepth "$d" ! -type d)"
for file in "${files[@]}"; do
file="$(tr -d '\n' <<< "$file")"
# implement your logic here
done
$files是一個帶有檔案名的陣列$f包含目錄$d是搜索的深度,默認是1(只針對指定檔案夾)$file包含檔案名$path_to_file/$filename
uj5u.com熱心網友回復:
你看到的
/var/spool/bandit24是空虛的結果。在這種情況下/var/spool/bandit24/*擴展為自身。如果您希望它擴展為 null,您可以nullglob在 for 回圈之前啟用 bash 選項:shopt -s nullglob。由于變數
myname被賦值bandit24,cd /var/spool/$myname是一樣的cd /var/spool/bandit24。您可能應該將其重寫為cd /var/spool/"$myname" || exit 1. 雙引號以防myname值包含空格(現在不是這種情況,但誰知道你接下來會做什么)。|| exit 1如果目錄不存在并且命令失敗,則中止腳本cd。這應該避免不必要的行為,例如執行和洗掉當前目錄中的所有腳本而不是不存在的腳本......使用
for file in /var/spool/bandit24/*,如果目錄不為空,變數file將采用類似的值/var/spool/bandit24/foobar,而不僅僅是foobar. 所以你不能將它與./$file. 解決方案:當你cd在/var/spool/bandit24目錄中時,只需撰寫for file in *.您真的應該雙引號參考所有對
$file(stat --format "%U" "$file",timeout -s 9 60 ./"$file",rm -f "$file") 的參考。如果你不這樣做,你就會冒真正的風險。
嘗試以下操作:
#!/bin/bash
myname="bandit24"
cd /var/spool/"$myname" || exit 1
echo "Executing and deleting all scripts in /var/spool/$myname:"
shopt -s nullglob
for file in *; do
echo "Handling $file"
owner=$(stat --format "%U" "$file")
if [ "$owner" = "$myname" ]; then
timeout -s 9 60 ./"$file"
fi
rm -f "$file"
done
uj5u.com熱心網友回復:
for f in $(find . -maxdepth 1 -type f); do
echo "current file is $f"
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/432623.html
標籤:重击
上一篇:獲取兩個正則運算式之間的字串
下一篇:如何洗掉游標后的所有內容?
