Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a file exist using adb shell

Tags:

android

shell

adb

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")
like image 580
darthvading Avatar asked Sep 12 '14 09:09

darthvading


People also ask

How do I search for a file in adb shell?

I used adb shell "ls -lR [ top-level-dir ]/[ varying number of */ ]/[ known part of filename ]> to find a glob pattern that matches the file, then started putting subdirs in the pattern - if the glob doesn't match, try the next subdir. It looked something like this: /lib/libSmth*.

How do you check if a file already exists in Linux?

Check if File Exists You can also use the test command without the if statement. The command after the && operator will only be executed if the exit status of the test command is true, test -f /etc/resolv. conf && echo "$FILE exists."


3 Answers

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" ]
like image 127
John B Avatar answered Oct 19 '22 20:10

John B


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
like image 5
LLL Avatar answered Oct 19 '22 20:10

LLL


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

like image 2
ligi Avatar answered Oct 19 '22 19:10

ligi