Check if file exists, and create file

hi i have 2 questions:

  1. how can i check if file exist in vi?
    i tryed to do:
    if [ -s $file ]; then
    echo file exist

but i get from the compiler
if: Expression Syntax.

  1. how can i create file in vi?
    when im using cat - so the script stop and wait for me to write somthing into the new file
    when im using touch - the file created, but i get the messege :
    touch: file arguments missing
    Try `touch --help' for more information.

???

Sounds to me like the variable "file" is not set.

If "file" is literally the name of the filename then you don't need the $ sign.

if [ -s file ] ...

touch file

Otherwise

file=myFile

if [ -s $file ] ...

touch $file

I think the proper construct is -e, however I am a novice shell programmer

#!/bin/bash

myfile="/path/to/my/file"

if [[ -e $myfile ]] 

    then /bin/echo "$myfile already exists"

    else /usr/bin/touch $myfile

fi

done

exit 0

The -e switch can only handle one file at a time, so if you want, you can build an array of file paths and loop it for checks. So, lets say you wanted to check for multiple files...

#!/bin/bash

myfile=(
           /path/to/my/file1
           /path/to/my/file2
           /path/to/my/file3
           /path/to/my/file4
           )

for file in "${myfile[@]}" ; do

if [[ -e $myfile ]] 

    then /bin/echo "$myfile already exists"

    else /usr/bin/touch $myfile

fi

done

exit 0

This will allow you to maintain a list of files to check, and if the file doesn't exist it will create it. Also, if this is run as root, it will create the file as root as the owner. So, you may have to add another part if you don't want root to own the file.