0

I am writing a bash function that takes an input as a file name and make sure it starts with an alpha character however the grep I am using to test the filename is accepting any input it is given

here is my code...

function getname(){
fname=$1;
if [ ! $1 ]; then
        read -p "Enter a file name: " fname;
fi;
until ( grep -E '^[a-zA-Z_]\w+' <<< "$fname" > /dev/null 2>1&); do
    if [ -d $fname ]; then
            echo "Paths are not a legal file name.";
        fi;
        read -p "Enter a legal file name: " fname;
done
}

it will properly accept either 1 or no parameters and prompt for a file name(if no parameter) but it will accept any string that is passed to it. so how would I properly grep the string stored as fname?

1
  • yes i was told to use grep for this assignment.
    – mike
    Commented Nov 17, 2017 at 0:24

2 Answers 2

3

I wouldn't use grep. Instead I would compare the filename using the built-in test operator ([[..]]), which can handle Regular Expressions directly.

function getname(){
    local fname="$1"

    [[ -z "$fname" ]] && read -p "Enter a file name: " fname

    until [[ "$fname" =~ ^[[:alpha:]] ]] && [[ -f "$fname" ]]
    do
        [[ -d $fname ]] && echo "Paths are not a legal file name."

        read -p "Enter a legal file name: " fname
    done
}
2

If you must use grep, then I suspect the issue with your implementation is that instead of 2>&1 (combine standard error and standard output) you wrote 2>1& (send standard error to a file called 1, and put the command into the shell background). This stops the grep exit status from being passed to the conditional.

FWIW you can use -q to exit silently, and I don't think you need the subshell at all - you could just write

until grep -qE '^[a-zA-Z_]\w+' <<< "$fname"; do

You must log in to answer this question.

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