Newbie.. Find if a file exists and open, if not create the desired file..

Hey all,
I'm brand new to script writing, I'm wanting to make a script that will ask for a file and then retrieve that file if it exists, and if it doesn't exist, create the file with the desired name, and I'm completely stuck.. so far..

#! bin/bash
echo "Enter desired file"
read "$file"
if [ -f $file ] ; then

...that's where i have no clue what to do, not even sure the first part is right..:wall:
any help would be awesome, reading man find, and man test right now to see if i can find something..

Use code tags

Try this

#! bin/bash
echo "Enter desired file"
read "$file"
if [ ! -f $file ] ; then
  touch $file #this will create the file
fi

And do you mean by retrieve the file?
regards,
Ahamed

1 Like

Thank you for the help, by retrieve, I mean it will look for the file, and if it exists already it will open it..

Again "open it" is a bit vague, do you want to "open it " in a pager such as less on the screen or "open it" in open office or open it in an editor like vi?

In each case above you invoke the command on the filename, most programs will recognise that there is no such file, and if the permissions allow it will create the file, pure viewers like less are the obvious exception to this rule.

Sorry for not being clear, it would have to be opened in vi ,

#! bin/bash
echo "Enter desired file"
read "$file"
if [ ! -f $file ] ; then
  touch $file #this will create the file
fi
vi $file

Please use code tags

1 Like