我正在嘗試通過使用函式設定一種靈活的方式來運行 find 命令。
我試過以下代碼:
#!/bin/bash
#
if [ $UID -ne 0 ]; then echo Please run this script as root; exit 1; fi
#
# create unique tmp file to store o/p
temp=$(basename $0)
TMPFILE=$(mktemp -q /tmp/${temp}.XXXXXX)
if [ $? -ne 0 ]; then
echo "$0: Can't create temp file, exiting..."
exit 1
fi
#
# create a function to store the find command
findCom () {
# $1 is the userid
local userid=$1
# $2 is the groupid
local groupid=$2
echo "in findCom"
echo "userid is $userid"
echo "groupid is $groupid"
echo "tmpfile is $TMPFILE"
commonComs='find / -not \( -path /proc -prune \) -not \( -path /sys -prune \) -not \( -path /usr/src -pru
ne \) -not \( -path /home -prune \) -not \( -path /dev -prune \) -not \( -path /tools -prune \) -not \( -
path /mnt -prune \) -not \( -path /blfs-commands -prune \) -not \( -path /blfs-html -prune \) -not \( -pa
th /blfs-sources -prune \) -not \( -path /blfsBuildFiles -prune \)'
userbit=' -user $userid '
groupbit='-group $groupid '
endbit='| sort -u > $TMPFILE'
finalCom="${commonComs}${userbit}${groupbit}${endbit}"
echo "$finalCom"
bash "$finalCom"
}
#
echo "tmpfile is $TMPFILE"
userid=gzip
groupid=gzip
findCom $userid $groupid
#find / -not \( -path /proc -prune \) -not \( -path /sys -prune \) -not \( -path /usr/src -prune \) -not
\( -path /home -prune \) -not \( -path /dev -prune \) -not \( -path /tools -prune \) -not \( -path /mnt -
prune \) -not \( -path /blfs-commands -prune \) -not \( -path /blfs-html -prune \) -not \( -path /blfs-so
urces -prune \) -not \( -path /blfsBuildFiles -prune \) \( -user $userid -a -group $groupid \) | sort -u
> $TMPFILE
如果我在主程式結束時運行 find 命令(注釋掉),它作業正常。如果我從函式中運行它,我會得到:
bash: find / -not \( -path /proc -prune \) -not \( -path /sys -prune \) -not \( -path /usr/src -prune \) -not \( -path /home -prune \) -not \( -path /dev -prune \) -not \( -path /tools -prune \) -not \( -path /mnt -prune \) -not \( -path /blfs-commands -prune \) -not \( -path /blfs-html -prune \) -not \( -path /blfs-sources -prune \) -not \( -path /blfsBuildFiles -prune \) -user $userid -group $groupid | sort -u > $TMPFILE: No such file or directory'
我認為這是引號的問題,但我嘗試了不同的引號,但找不到讓它起作用的方法。
任何幫助將非常感激。
uj5u.com熱心網友回復:
我認為您需要使用它來執行最終命令:
bash -c "$finalCom"
沒有-c您要求 bash 執行 file/path $finalCom。
uj5u.com熱心網友回復:
我建議使用陣列來存盤要執行的 find 命令:
findcommand=("find" "/" "-not" ...)
findcommand =("-user" "$userid")
findcommand =("-group" "$groupid")
echo "${findcommand[@]}"
"${findcommand[@]}" | sort -u > "$TMPFILE"
這應該更安全,更靈活,并且還可以更好地處理空間和逃逸之類的事情。
話雖如此,您還應該注意'<str>'和之間存在差異"<str>"。我想你想在這里使用雙引號:
userbit=" -user $userid"
groupbit=" -group $groupid"
endbit=" | sort -u > $TMPFILE"
使用單引號,你會得到一個字串。使用雙引號,變數(此處為$userid, $groupid, $TMPFILE)用它們的值進行擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327048.html
上一篇:如何在SASS[scale-color]函式中使用CSS變數?
下一篇:如何在SQL的新列中顯示每個值
