搜索文件/目录的shell脚本

  • 在 Windows 下,有一款非常实用的神器,叫作 Everything ,它可以在极短的时间里,搜索出来你所想要的文件/目录
  • Linux 下也有一些类似于 everything 的神器,比如:locate,Catfish,Tracker,等等。这些工具也十分强大,但是自己动手丰衣足食,说干就干:
  1. vim创建一个脚本文件
  2. 1 [root@izgt88z6l1kvd7z ~]# vim Anyfile.sh

    代码如下:

  3.  1 [root@izgt88z6l1kvd7z ~]# vim Anyfile.sh
     2 [root@izgt88z6l1kvd7z ~]# cat Anyfile.sh 
     3 #!/bin/sh
     4 
     5 ## help function
     6 
     7 function helpu {
     8     echo " "
     9     echo "Fuzzy search for filename."
    10     echo "$0 [--match-case|--path] filename"
    11     echo " "
    12     exit
    13 }
    14 
    15 ## set variables
    16 
    17 MATCH="-iname"
    18 SEARCH="."
    19 
    20 ## parse options
    21 
    22 while [ True ]; do
    23 if [ "$1" = "--help" -o "$1" = "-h" ]; then
    24     helpu
    25 elif [ "$1" = "--match-case" -o "$1" = "-m" ]; then
    26     MATCH="-name"
    27     shift 1
    28 elif [ "$1" = "--path" -o "$1" = "-p" ]; then
    29     SEARCH="${2}"
    30     shift 2
    31 else
    32     break
    33 fi
    34 done
    35 
    36 ## sanitize input filenames
    37 ## create array, retain spaces
    38 
    39 ARG=( "${@}" ) 
    40 set -e
    41 
    42 ## catch obvious input error
    43 
    44 if [ "X$ARG" = "X" ]; then
    45     helpu
    46 fi
    47 
    48 ## perform search
    49 
    50 for query in ${ARG[*]}; do
    51     /usr/bin/find "${SEARCH}" "${MATCH}" "*${ARG}*"
    52 done
  4. 然后给它执行的权限,我给最大的777
  5. 1 [root@izgt88z6l1kvd7z ~]# chmod 777 Anyfile.sh
  6. 试一下,搜索sed
  7. 1 [root@izgt88z6l1kvd7z ~]# ./Anyfile.sh sed
    2 ./administration/git/git-2.26.2/t/chainlint.sed
    3  
  8. 使用 alias 命令,来实现别名ss=./Anyfile.sh。为了能够在系统重启之后ss命令依然能使用,我们直接在 .bashrc 里进行修改。
  9. alias 'lol'='/root/Anyfile.sh'

    按x退出执行一下

  10.  . ~/.bashrc

    再次实验

    [root@izgt88z6l1kvd7z ~]# lol my
    ./administration/git/git-2.26.2/t/t4051/dummy.c
    ./administration/git/git-2.26.2/Documentation/MyFirstObjectWalk.txt
    ./administration/git/git-2.26.2/Documentation/MyFirstContribution.txt
    ./administration/my.cnf
    ./.mysql_history

    ok

原文地址:https://www.cnblogs.com/hxlinux/p/12845321.html