1

I set up: read -p "What will you like to name the file name? " filename. However if the user inputs more than a word the script will break down. How do I detect the user input to have more than one word?

Sorry! This is the code:

# provide option to rename the .ph file

while true do # user prompt for rename file and read command line argument read -p "Would you like to change the file name? (Y/N) " answer

# Handle user input
case $answer in
    [Yy]* ) 
    echo "Please enter a single word for file name. Otherwise the file name will be sequence.ph."
    read -p "What will you like to name the file name? " filename
    newname="$filename"
    mv sequence.ph $filename.ph
    echo "File has been renamed." 
    break
    ;;
[Nn]* )
newname="$1_tree"
mv sequence.ph $newname.ph
echo "Output file will have default name $1_tree.ph"
break
;;
* )
echo "Error: Invalid input."  
echo "Please enter y/Y or n/N. "
;;

esac done

Jerry
  • 161
  • 1
    Your issue is likely not to do with reading space-separated words, but with using $filename and $newname unquoted. Possible duplicate: https://unix.stackexchange.com/questions/131766 – Kusalananda Nov 07 '20 at 10:57

1 Answers1

1

If you give the read command multiple variables to read into, it'll try to split the input into words and store one word per variable. Thus, you can give it two variables, and if the second has anything in it, more than one word was input. Something like this:

while true; do
    read -r -p "What will you like to name the file name? " filename extra    # $extra will contain any extra word(s)
    if [ -n "$extra" ]; then
        echo "One-word filenames only, please"
    else
        break    # Got a valid filename, so break out of the loop
    fi
done

Note: I also added the -r option to read to keep it from doing weird things with backslashes. Probably not needed, but a generally good habit.

...but multi-word filenames shouldn't really be a problem. Handling them properly can be a little tricky for some advanced operations (see BashFAQ #20), but for basic use you just need to put double-quotes around your variable references. Like this:

cat "$filename"    # Works with multi-word filenames
cat $filename    # FAILS with multi-word filenames - don't do this

Double-quoting variable references is a good idea in general, so you should do it even if you don't allow (/expect) them to contain multiple words. shellcheck.net is good at pointing out places where variables should be double-quoted, as well as a bunch of other common scripting mistakes (including omitting the -r option to read), so I recommend running your scripts through it.