无法从函数中 运行 查找命令

Unable to run the find command from within a function

我正在尝试设置一种灵活的方式 运行通过使用一个函数来执行查找命令。

我试过以下代码:

#!/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 [=11=])
TMPFILE=$(mktemp -q /tmp/${temp}.XXXXXX)
if [ $? -ne 0 ]; then
  echo "[=11=]: Can't create temp file, exiting..."
  exit 1
fi
#
# create a function to store the find command
findCom () {
#  is the userid
local userid=
#  is the groupid
local groupid=
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'

我认为这是引号的问题,但我尝试了不同的引号,但找不到让它工作的方法。

如有任何帮助,我们将不胜感激。

我想你需要用这个来执行最后的命令:

bash -c "$finalCom"

没有 -c 你要求 bash 执行 file/path $finalCom.

我建议使用数组来存储您要执行的查找命令:

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)用它们的值展开。