我想編譯一個非常簡單的bash腳本,它將執行以下操作(我迄今爲止的腳本看起來沒有任何功能,所以我不會浪費時間把這個給你看看)Bash腳本 - 通過用戶輸入查找文件
我需要它通過他們的名字找到文件。我需要腳本來接受用戶輸入並在.waste目錄中搜索匹配項,如果文件夾爲空,我需要回顯「找不到匹配項,因爲該文件夾是空的!」,並且通常無法找到匹配一個簡單的「找不到匹配」。
我已經定義:target=/home/user/bin/.waste
我想編譯一個非常簡單的bash腳本,它將執行以下操作(我迄今爲止的腳本看起來沒有任何功能,所以我不會浪費時間把這個給你看看)Bash腳本 - 通過用戶輸入查找文件
我需要它通過他們的名字找到文件。我需要腳本來接受用戶輸入並在.waste目錄中搜索匹配項,如果文件夾爲空,我需要回顯「找不到匹配項,因爲該文件夾是空的!」,並且通常無法找到匹配一個簡單的「找不到匹配」。
我已經定義:target=/home/user/bin/.waste
您可以使用內置的find命令來做到這一點
find /path/to/your/.waste -name 'filename.*' -print
或者,你可以在你.bash_profile
searchwaste() {
find /path/to/your/.waste -name "$1" -print
}
它設置爲功能請注意,在$1
附近有引號。這將允許你做文件通配。
searchwaste "*.txt"
上面的命令將搜索您.waste
目錄中的任何文件.txt
在這裏,你走了,很簡單的腳本:
#!/usr/bin/env bash
target=/home/user/bin/.waste
if [ ! "$(ls -A $target)" ]; then
echo -e "Directory $target is empty"
exit 0
fi
found=0
while read line; do
found=$[found+1]
echo -e "Found: $line"
done < <(find "$target" -iname "*$1*")
if [[ "$found" == "0" ]]; then
echo -e "No match for '$1'"
else
echo -e "Total: $found elements"
fi
順便說一句。在* nix的世界裏有沒有文件夾,但也有目錄 :)
這是一個解決方案。
#!/bin/bash
target="/home/user/bin/.waste"
read name
output=$(find "$target" -name "$name" 2> /dev/null)
if [[ -n "$output" ]]; then
echo "$output"
else
echo "No match found"
fi
我之前沒有碰到過globbing,實際上我只是在今天才瞭解到這個概念,我需要爲這個腳本工作還是沒有它我就沒事了?我不知道該怎麼做 – Syler