1. 程式人生 > 實用技巧 >自定義linux系統檔案搜尋指令碼

自定義linux系統檔案搜尋指令碼

1. 新建search.sh指令碼,寫入以下shell指令碼:

#!/bin/sh
# lazy find
# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.
## help function
function helpu {
    echo 
" " echo "Fuzzy search for filename." echo "$0[--match-case|--path] filename" echo " " exit } ## set variables MATCH="-iname" SEARCH="." ## parse options while [ True ]; do if [ "$1" = "--help" -o "$1" = "-h" ]; then helpu elif [ "$1" = "--match-case" -o "$1" = "-m" ]; then MATCH
="-name" shift 1 elif [ "$1" = "--path" -o "$1" = "-p" ]; then SEARCH="${2}" shift 2 else break fi done ## sanitize input filenames ## create array, retain spaces ARG=( "${@}" ) set -e ## catch obvious input error if [ "X$ARG" = "X" ]; then helpu fi ## perform search for query in ${ARG[*]}; do
/usr/bin/find "${SEARCH}" "${MATCH}" "*${ARG}*" done

2. 賦予指令碼可執行許可權:

chmod +x search.sh

3. 使用

sh search.sh hello ## 在當前目錄下遍歷搜尋帶hello關鍵字的所有檔案

sh search --path /usr/local hello ##在指定目錄/usr/local下搜尋帶關鍵字hello的所有檔案

4. 新增到系統快捷命令

vim ~/.bashrc ##編輯系統命令

新增:

alias lf=/root/find_file.sh ##自定義檔案搜尋指令碼

儲存生效:

. ~/.bashrc

5. 使用快捷命令搜尋檔案

lf hello 或者 lf --path /usr/local hello