简体   繁体   English

无法在 bash 脚本中执行查找命令

[英]Find command cannot be executed inside bash script

I wrote a bash script to retrieve the last few days file info from the file system, and the file under some sub-folders will be excluded.我写了一个bash脚本来从文件系统中检索最近几天的文件信息,一些子文件夹下的文件会被排除在外。 Here is the script(test.sh):这是脚本(test.sh):

#!/bin/bash
date_range=$1
base_dir=$2
excluded_dir=$3

# Command initialization
cmd="find $base_dir"
for item in ${excluded_dir[@]}
do
  cmd="$cmd -not \( -path '$base_dir/$item' -prune \)"
done
cmd="$cmd -type f -mtime -$date_range -ls"
echo $cmd

$cmd

I tried an example as below:我尝试了一个例子,如下所示:

./test.sh 3 /root "excluded_folder1 excluded_folder2" 

The command has been initialized as:该命令已初始化为:

find /root -not \( -path '/root/excluded_folder1' -prune \) -not \( -path '/root/excluded_folder2' -prune \) -type f -mtime -3 -ls

If I run this find command in my terminal, it works fine, I can get the results that I want.如果我在我的终端中运行这个find命令,它工作正常,我可以获得我想要的结果。 While if it's executed in the bash script.而如果它是在 bash 脚本中执行的。 I always get such an error:我总是收到这样的错误:

find: paths must precede expression: \(
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Does anybody knows what is the problem and how to fix this?有谁知道是什么问题以及如何解决这个问题?

Thanks for all the answers and suggestions I received here.感谢我在这里收到的所有答案和建议。 But none of that solved my problem.但这些都没有解决我的问题。 The problem is finally solved by using 'eval' to execute the command.问题最终通过使用'eval'执行命令解决。 The final working bash script is as below:最终的工作 bash 脚本如下:

#!/bin/bash
date_range=$1
base_dir=$2
excluded_dir=$3

# Command initialization
cmd="find $base_dir"
for item in ${excluded_dir[@]}
do
  cmd="$cmd -not \( -path '$base_dir/$item' -prune \)"
done
cmd="$cmd -type f -mtime -$date_range -ls"

eval $cmd

While there're some posts saying using eval in bash script is a bad and insecure choice, I still don't know how can I solve this problem with some other approaches.虽然有一些帖子说在 bash 脚本中使用eval是一个糟糕且不安全的选择,但我仍然不知道如何用其他方法解决这个问题。 If someone got a better idea, please post it here.如果有人有更好的主意,请在此处发布。

Reference:参考:

  1. What is the eval command in bash? bash 中的 eval 命令是什么?
  2. Why and when should eval use be avoided in shell scripts? 为什么以及何时应该在 shell 脚本中避免使用 eval?

Based on my guess above, I suggest the following code:根据我上面的猜测,我建议使用以下代码:

#!/bin/bash
date_range=$1
base_dir=$2
excluded_dir=$3

# Command initialization
cmd="find $base_dir"
for item in ${excluded_dir[@]}
do
  cmd="$cmd -not ( -path '$base_dir/$item' -prune )"
done
cmd="$cmd -type f -mtime -$date_range -ls"
echo $cmd

$cmd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM