gpt4 book ai didi

linux - find 命令适用于提示,而不是 bash 脚本 - 通过变量传递多个参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:25 25 4
gpt4 key购买 nike

我搜索了具有类似问题的问题,但没有找到完全适合我情况的问题。

下面是一个非常简短的脚本,演示了我面临的问题:

#!/bin/bash

includeString="-wholename './public_html/*' -o -wholename './config/*'"
find . \( $includeString \) -type f -mtime -7 -print

基本上,我们需要在一个文件夹中搜索,但只在其某些子文件夹中搜索。在我较长的脚本中,includeString 是从数组构建的。对于这个演示,我让事情变得简单。

基本上,当我运行脚本时,它找不到任何东西。没有错误,但也没有命中。如果我手动运行 find 命令,它就可以工作。如果我删除 ( $includeString ) 它也可以工作,但显然它不限于我想要的文件夹。

那么,为什么相同的命令可以在命令行中运行,而不能在 bash 脚本中运行呢?以这种方式传递 $includeString 会导致它失败的原因是什么?

最佳答案

您遇到了 shell 如何处理变量扩展的问题。在你的脚本中:

includeString="-wholename './public_html/*' -o -wholename './config/*'"
find . \( $includeString \) -type f -mtime -7 -print

这导致 find寻找 -wholename 所在的文件匹配文字串 './public_html/*' .即,包含单引号的文件名。由于您的路径中没有任何空格,因此这里最简单的解决方案是只删除单引号:

includeString="-wholename ./public_html/* -o -wholename ./config/*"
find . \( $includeString \) -type f -mtime -7 -print

不幸的是,您可能会在这里遇到通配符扩展问题(shell 会在 find 看到它们之前尝试扩展通配符)。

但正如 Etan 在他的评论中指出的那样,这似乎不必要地复杂;你可以简单地做:

find ./public_html ./config -type f -mtime -7 -print

关于linux - find 命令适用于提示,而不是 bash 脚本 - 通过变量传递多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com