0

I'm trying to compile a very simple bash script that will do the following actions (the script I have so far doesn't seem to function at all so I won't waste time putting this up for you to look at)

I need it to find files by their names. I need the script to take the user input and search the .waste directory for a match, should the folder be empty i'd need to echo out "No match was found because the folder is empty!", and just normally failing to find a match a simple "No match found."

I have defined: target=/home/user/bin/.waste

3 Answers 3

1

You can use the built in find command to do this

find /path/to/your/.waste -name 'filename.*' -print

Alternatively, you can set this as a function in your .bash_profile

searchwaste() {
  find /path/to/your/.waste -name "$1" -print
}

Note that there are quotes around the $1. This will allow you to do file globbing.

searchwaste "*.txt"

The above command would search your .waste directory for any .txt files

Sign up to request clarification or add additional context in comments.

1 Comment

I haven't touched globbing before, in fact I only learned of the concept today, will I need to do it for this script to work or am I fine without it? I'd have no idea what to do heh
0

Here you go, pretty straightforward script:

#!/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

Btw. in *nix world there are not folders, but there are directories :)

Comments

0

This is a solution.

#!/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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.