0

I am making simple Shell script form some boring-ever-repeating job. Script changes directory correctly, and now I want to run other scripts based on argument I typed when running script. Other scripts are scattered in subdirectories and each one is unique. So I want to insert just file name and let script find out in which subdirectory is that file.

I tried something like this:

filename="default.ini"
while [ $# -gt 0 ] 
do
    case "$1" in
        -f) filename="$(find ./ -name $2)"; shift;;
        -*) echo >&2 \
            "usage: $0 [-v] [-f file] [file ...]"
            exit 1;; 
        *)  break;;     # terminate while loop
    esac
    shift
done

echo $filename

But, find doesn’t return any result, so it stays default.ini. Is there other way to solve this?

1
  • is find's ./ actually what you think is should be? Is find looking in the right directory? May 14, 2014 at 16:00

1 Answer 1

1

I would suggest that this is a more idiomatic way of parsing options:

filename="default.ini"
v_opt=false

while getopts :vf: opt; do
    case $opt in 
        f) find_out=$(find . -name "$OPTARG") 
           # do something with $find_out, such as checking if it's empty, or
           # if more than one file was found ...
           [[ $find_out ]] && filename=$(head -n 1 <<< "$find_out")
           ;;
        v) v_opt=true ;;
        ?) echo "usage: ..."; exit 1;;
    esac
done
shift $((OPTIND-1))

echo $filename

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .