简体   繁体   English

从Java执行时,Linux脚本无法正常工作

[英]Linux Script does not work properly when execute from Java

I have this Script that simply mount the attached External drive and write their mounted path in a text file. 我有这个脚本,可以简单地安装附加的外部驱动器,并将其安装路径写入文本文件。 Though when I run this script from terminal in tinyCOre it works fine. 虽然当我从tinyCOre的终端运行此脚本时,它仍然可以正常工作。 Following is the Code I am using to execute the script, I am using this code throughout my application for mounting and other purposes but non of them have writing to do. 以下是我用来执行脚本的代码,我在整个应用程序中都使用此代码来进行挂载和其他用途,但其中没有一个需要编写。

Code: 码:

  Process p = Runtime.getRuntime().exec(" sh /home/abc/mnt-ddc.sh");
   p.waitFor();

I even tried taking the script as array but no help. 我什至尝试将脚本作为数组,但没有帮助。 Quick help will be appreciated. 快速帮助将不胜感激。 Thanks. 谢谢。

UPDATE WHen the script is executed from java, nothing happens, no exception thrown, no nothing. 更新从Java执行脚本后,什么也没有发生,没有抛出异常,没有任何反应。 I tried all the ways answered below none working. 我尝试了所有无法解决的方法。

mnt-ddc.sh mnt-ddc.sh

#!/bin/sh
blkid -s LABEL | grep ddc- > ddc.txt        # Get DDC device name and label and write to ddc.txt

perl -pi -e 's/ LABEL="//g' ddc.txt     # Remove text "ddc- from ddc.txt

#perl -pi -e 's/ LABEL="ddc-//g' ddc.txt        # Remove text "ddc- from ddc.txt
perl -pi -e 's/" //g' ddc.txt           # Remove left over text " from ddc.txt

while IFS=: read dev label          # start loop and read device name to $dev and LABEL to $label
do

if mount | grep $dev; then
   echo -e "Already mounted"
else
    if [ ! -d /mnt/$label ]; then
       echo -n "Creating mount point..."
       sudo mkdir /mnt/$label
    fi
        echo -n "Mounting......"$label
    sudo mount $dev /mnt/$label
        echo
    if [ "$?" != "0" ]; then
        echo "Mount failed.  Exiting."
        echo "" > ddc.txt
        exit
    fi
fi

done < ddc.txt

Did you notice the space in front of "sh"? 您是否注意到“ sh”前面的空间? Why spawn a new shell? 为什么要产生新的外壳? I would make the script directly executable (eg chmod +x /home/paftdl/NavData/mnt-ddc.sh ) and then just call it - 我将使脚本直接可执行(例如chmod +x /home/paftdl/NavData/mnt-ddc.sh ),然后直接调用它-

Process p = Runtime.getRuntime().exec("/home/paftdl/NavData/mnt-ddc.sh");
InputStream is = p.getInputStream(); // Let's print what we get.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
  System.out.println(line);
}

Although it is better to use ProcessBuilder 虽然最好使用ProcessBuilder

The problem you are having is that you have a space in front of sh 您遇到的问题是sh前面有一个空格

Process p = Runtime.getRuntime().exec("sh /home/paftdl/NavData/mnt-ddc.sh");
p.waitFor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM