5

I have a bash script which goes as follows

if [ -f "/sdcard/testfile"]
then 
echo "exists" > /sdcard/outfile
else
echo "does not exist" > /sdcard/outfile
fi

I have sufficient permission to run this with /system/bin/sh. I am calling this script from my application and running this with /system/bin/sh. But after running I am getting false, even if the file '/sdcard/testfile' is there. When I am explicitly running in adb shell, I am getting this error

[: not found

Is there any other way to accomplish this task? I cannot just use java.io.File because of permission issue of application; therefore, I am adhering to shell script (command).

I need the output in the application itself. I mean,

if(filesAreAvailable)
    executeSomething();
else
    executeSomethingElse();

Basically I am programmatically writing this script in the /data/data/myPackageName/files directory and for calling the command:

if [ -f "/sdcard/testfile"]

as

fileWriterScript.write("if [ -f \"/sdcard/testfile\" ]\n")
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
darthvading
  • 859
  • 2
  • 10
  • 23

5 Answers5

7

When using test, you need a space after the opening bracket and before the closing bracket.

From man test:

SYNOPSIS
    test expression
    [ expression ]

So change:

[ -f "/sdcard/testfile"]

to:

[ -f "/sdcard/testfile" ]
John B
  • 3,466
  • 1
  • 14
  • 20
5

If you need to use this in bash script then you can do it that way:

if [[ `adb shell ls /sdcard/path/to/your.file 2> /dev/null` ]]; then
    echo "File exists";
else
    echo "File doesn't exist";
fi
LLL
  • 1,600
  • 1
  • 14
  • 28
2

you could do a ls and then check the output - when it contains "No such file or directory" - the file is not there. But still IMHO you need the permission

ligi
  • 37,862
  • 40
  • 132
  • 234
1

I used this script. It's checking if a file exist on the phone.

#!/bin/bash

RESULT=$(adb shell "[ -f $1 ] || echo 1")

if [ -z "$RESULT" ]; then
    echo "File exists!"
else
    echo "File not found!"
fi
J.H.
  • 11
  • 2
0

I made it work using another answer posted in stackoverflow. Reference https://stackoverflow.com/a/6364244/2031060

Community
  • 1
  • 1
darthvading
  • 859
  • 2
  • 10
  • 23