batch scripting – if exist ./sdcard/file.any using adb

Running in a command prompt window if /? or help if outputs the help pages for internal command if.

The command processor is not very tolerant on syntax. An else branch is only possible with using parentheses. The true branch must have ( which must be on same line as command if separated with a space from last argument of the condition.

The closing ) for true branch can be on same line as opening ( or on a different line.

The keyword else must be on same line as closing ) of the true branch after a space.

If round brackets are used also for the else branch, opening ( must be on same line as else separated with a space from the keyword.

The keyword do is completely wrong here as it is a keyword for command FOR.

Some of the working variants.

  1. Everything on one line with as less spaces as possible (hard to read):

     if exist "directory\file" (echo exists) else (adb push "file" "directory")
    
  2. Everything on one line with more spaces for easier reading:

     if exist "directory\file" ( echo exists ) else ( adb push "file" "directory" )
    
  3. Condition on first line, true branch on second line, else branch without parentheses on third line:

     if exist "directory\file" (
         echo exists
     ) else adb push "file" "directory"
    
  4. Each part of the entire condition on separate lines:

     if exist "directory\file" (
         echo exists
     ) else (
         adb push "file" "directory"
     )
    

There are more variants possible, but they are all horrible to read.

It is best to use second or fourth variant as those two are the best for reading.

I recommend to use always fourth variant if an else branch is used, too.

.\ at beginning of file name / directory name could be omitted.

And the directory separator on Windows is the backslash character.

NOTE: I don’t know if if exist ./sdcard/file.any or .\sdcard\file.any works at all. The question does not contain any information about

  • Android version,
  • the Android device itself,
  • how the device is configured regarding to accessing files and directories on its storage medias – as removable storage(s) making it possible to access the files and directories from Windows command line environment or just via Media Transfer Protocol which is not supported from Windows command line environment,
  • in which environment this batch file is running, i.e. what is the current directory, what are the values of the environment variables PATH and PATHEXT, etc.

So the answer covers only the IF syntax mistake, not how to check for existence of a file on any Android device with any Android version connected with whatever device drivers and data storage accessing protocols are used for accessing the device.

Leave a Comment