我正在尝试编写一个函数,它接收像 f hello there my friend
这样的参数,并使用 find
在目录中搜索任何一个字符串的所有出现,因此它将是 find | grep 'hello\|there\|my\|friend'
。 我对shell脚本不太熟悉,但我的代码如下:
function f {
cmd="find | grep '"
for var in "$@"
do
cmd="$cmd$var\\|"
done
cmd="${cmd%\\|}'"
echo "$cmd"
$cmd
}
当我执行该命令时,我会得到这个结果:
# f hello there my friend
find | grep 'hello\|there\|my\|friend'
find: `|': No such file or directory
find: `grep': No such file or directory
find: `\'hello\\|there\\|my\\|friend\'': No such file or directory
为什么它不起作用,我该如何使其起作用?我想这可能与字符串没有被转换为命令有关,但我对shell脚本的工作原理了解不够,无法找出问题所在。
if diff file1 file2 >/dev/null ; then echo "file1 and file2 are identical" fi
diff 命令将会输出不同之处。如果没有输出,说明两个文件相同。由于只需要判断文件是否相同,我们将其重定向到 /dev/null 中以丢弃所有输出。还有一个更好的方法是使用 cksum 命令:if [ "$(cksum file1)" = "$(cksum file2)" ] ; then echo "file1 and file2 are identical" fi
cksum 命令会生成一个校验和并输出到 stdout。通过比较两个文件的校验和能够确定它们是否相同。注意,这种方法不是百分之百可靠的,尤其是当两个文件大小相同时。另外,您也可以使用 md5sum 或 sha1sum 等工具来获取文件的摘要,并比较它们是否相同。 - Biffengrep -r
命令搜索内容。 - ewok