linux - 试图创建一个文件来调用另一个文件进行循环搜索

标签 linux bash shell scripting

我正在尝试编写一个脚本来调用另一个脚本并根据输入使用一次或循环使用它。

我编写了一个脚本,它只在文件中搜索模式,然后打印文件名并列出找到搜索的行。该脚本在这里

#!/bin/bash

if [[ $# < 2 ]]
then
  echo "error: must provide 2 arguments."
  exit -1
fi

if [[ -e $2 ]]
then
    echo "error: second argument must be a file."
    exit -2
fi

echo "------ File =" $2 "------"
grep -ne $1 $2

所以现在我想写一个新的脚本,如果用户只输入一个文件作为第二个参数,它会调用它,如果他们选择一个目录,也会循环并搜索目录中的所有文件。

所以如果输入是:

./searchscript if testfile

它只会使用脚本,但如果输入是:

./searchscript if Desktop

它将循环搜索所有文件。

一如既往,我的心为你们所有人倾倒。

最佳答案

类似的东西可以工作:

#!/bin/bash

do_for_file() {
    grep "$1" "$2"
}

do_for_dir() {
    cd "$2" || exit 1
    for file in *
    do
        do_for "$1" "$file"
    done
    cd ..
}

do_for() {
    where="file"
    [[ -d "$2" ]] && where=dir
    do_for_$where "$1" "$2"
}

do_for "$1" "$2"

关于linux - 试图创建一个文件来调用另一个文件进行循环搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17220746/

相关文章:

c++ - 谁可以发送到绑定(bind)到 INADDR_LOOPBACK 的套接字?

bash - 更新 bash 中 watch 命令中的变量

bash - telnet redis bash 脚本

Python3移植问题

python - 如何对多个文件使用 unix/shell 粘贴命令

python - 哪个python正在运行?

c - GCC 无法编译 libcurl 示例 : ‘CURLINFO_TOTAL_TIME_T’ undeclared

linux - bcp 格式文件并 -c 切换出去

Bash 函数 -> 找不到命令

linux - 为什么 shell 在后台进程中忽略 SIGINT 和 SIGQUIT?