如何使用adb shell检查文件是否存在

时间:2014-09-12 09:47:38

标签: android shell adb

我有一个bash脚本,如下所示

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

我有足够的权限与/system/bin/sh一起运行。 我从我的应用程序调用此脚本并使用/system/bin/sh运行此脚本。 但是在运行之后,我变得虚假,即使文件' / sdcard / testfile'在那儿。 当我在adb shell中明确运行时,我收到此错误

[: not found

还有其他方法可以完成这项任务吗?由于应用程序的权限问题,我不能只使用java.io.File;因此,我坚持使用shell脚本(命令)。

我需要应用程序本身的输出。我的意思是,

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

基本上我是以编程方式在/data/data/myPackageName/files目录中编写此脚本并调用命令:

if [ -f "/sdcard/testfile"]

作为

fileWriterScript.write("if [ -f \"/sdcard/testfile\" ]\n")

5 个答案:

答案 0 :(得分:5)

使用test时,您需要在左括号后面和结束括号前的空格。

来自man test

SYNOPSIS
    test expression
    [ expression ]

所以改变:

[ -f "/sdcard/testfile"]

为:

[ -f "/sdcard/testfile" ]

答案 1 :(得分:2)

如果你需要在bash脚本中使用它,那么你可以这样做:

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

答案 2 :(得分:1)

你可以做一个ls然后检查输出 - 当它包含“没有这样的文件或目录”时 - 文件不在那里。但仍然恕我直言,你需要许可

答案 3 :(得分:0)

我使用stackoverflow中发布的另一个答案使其工作。参考 https://stackoverflow.com/a/6364244/2031060

答案 4 :(得分:0)

我使用了这个脚本。它正在检查手机上是否存在文件。

#!/bin/bash

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

if [ -z "$RESULT" ]; then
    echo "File exists!"
else
    echo "File not found!"
fi