Bash 脚本错误:'find: paths must precede expression' 的解决方法

在使用 find 命令时,可能会遇到错误提示 'find: paths must precede expression'。这个错误提示意味着在 find 命令中,路径应该在表达式之前。

原因:

这个错误通常是因为文件名中包含空格或其他特殊字符,导致 find 命令无法识别文件路径。

解决方法:

将文件名用引号括起来,例如:

find '$dir' -name '*.c'

示例脚本:

以下是一个使用 find 命令统计目录下所有 .c 文件的行数的脚本:

#!/bin/bash
if [ $# = 0 ]
  then echo 'Usage: $0 Directory'
  exit 1
fi
test ! -d $1 && echo '$1 is not a Directory!' && exit 1
dir=$1
sum=0
for i in `find '$dir' -name '*.c'`
do
  echo $i
  lines=`wc -l < $i`
  sum=`expr $sum + $lines`
done
echo 'The total lines is $sum.'

解释:

  • 使用 find '$dir' -name '*.c' 将目录路径和文件名用引号括起来,确保 find 命令能够正确识别文件路径。
  • 使用 wc -l < $i 统计每个文件中的行数。
  • 使用 expr $sum + $lines 计算所有文件的总行数。

注意事项:

  • 确保脚本具有可执行权限。
  • 脚本中的 Directory 应替换为实际的目录路径。
  • 脚本中的 *.c 可根据需要修改为其他文件类型。
Bash 脚本错误:find: paths must precede expression: 解决方法

原文地址: https://www.cveoy.top/t/topic/gP9q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录