0

I'm currently writing a script, and at one point I want it check if a file already exists. If the file doesn't exist, then it should do nothing. However, if the file does exist, I want a 'y' or 'n' (yes or no) menu to appear. It should ask "Do you want to overwrite this file?".

So far I've tried writing something similar to this. Take into account that before this a function called:

therestore

exists. I want this function to occur if they type "y". Anyway, this is what I tried:

If [ -f directorypathANDfilename ] ; then
 read -p "A file with the same name exists, Overwrite it? Type y/n?" yesorno
    case $yesorno in
            y*)  therestore ;;
            n*)  echo "File has not been restored" ;;
    esac
fi

For some reason though, the menu always pops up, even if the file DOESN'T exist and it doesn't restore it properly if I type yes! (But I know the "therestore" function works fine, because I've tested it plenty of times).

Apologies for the long-winded question. If you need any more details let me know - thanks in advance!

0

1 Answer 1

2

Does your script even run? Doesn't look like valid bash-script to me. If is not a valid keyword, but if is. Also, tests go inside angle-brackets [ ], those are not optional. Moreover you forgot the closing fi.
And another thing, it's not quite clear to me what you're testing for. Is directorypathANDfilename a variable? In that case you have to reference it with the $.

The snippet would probably work better like this:

#!/bin/bash

if [ -f "$directorypathANDfilename" ] ; then
 read -p "A file with the same name exists, Overwrite it? Type y/n?" yesorno
    case "$yesorno" in
            y*)  therestore ;;
            n*)  echo "File has not been restored" ;;
    esac
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Oos! I forgot to add the 'test' statement and the closing fi - thanks for doing that! In the original script however I did have both of those elements included, and I still had the problems. Also, why doesn't this look like a bash script?? Cheers!

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.