Question

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!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top