2015-07-11 147 views
1

我有一個創建一個包含從我的相機的當前設置一個文本文件中的shell腳本:腳本未正確執行

#!/bin/sh 
file="test.txt" 
[[ -f "$file" ]] && rm -f "$file" 

var=$(gphoto2 --summary) 
echo "$var" >> "test.txt" 


if [ $? -eq 0 ] 
then 
    echo "Successfully created file" 
    exit 0 
else 
    echo "Could not create file" >&2 
    exit 1 
fi 

該腳本,因爲我認爲它應該當我運行它從終端,但是當我運行下面的處理程序是創建的文本文件,但不包含任何來自相機的信息:

import java.util.*; 
import java.io.*; 

void setup() { 
    size(480, 120); 
    camSummary(); 
} 

void draw() { 
} 
void camSummary() { 
    String commandToRun = "./ex2.sh"; 
    File workingDir = new File("/Users/loren/Documents/RC/CamSoft/"); 
    String returnedValues; // value to return any results 


    try { 
     println("in try"); 
     Process p = Runtime.getRuntime().exec(commandToRun, null, workingDir); 
     int i = p.waitFor(); 
     if (i==0) { 
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      while ((returnedValues = stdInput.readLine()) != null) { 
      println(returnedValues); 
      } 
     } else{ 
      println("i is: " + i); 
     } 
    } 
    catch(Throwable t) { 
     println(t); 
    } 
} 

最後,我想直接從劇本到讀取一些數據變量,然後在處理中使用這些變量。

有人可以幫我解決這個問題嗎?

謝謝

羅蘭

備用腳本:

#!/bin/sh 

set -x 
exec 2>&1 

file="test.txt" 
[ -f "$file" ] && rm -f "$file" 


# you want to store the output of gphoto2 in a variable 
# var=$(gphoto2 --summary) 
# problem 1: what if PATH environment variable is wrong (i.e. gphoto2 not accessible)? 
# problem 2: what if gphoto2 outputs to stderr? 
# it's better first to: 

echo first if 
if ! type gphoto2 > /dev/null 2>&1; then 
    echo "gphoto2 not found!" >&2 
    exit 1 
fi 

echo second if 
# Why using var?... 
gphoto2 --summary > "$file" 2>&1 
# if you insert any echo here, you will alter $? 
if [ $? -eq 0 ]; then 
    echo "Successfully created file" 
    exit 0 
else 
    echo "Could not create file" >&2 
    exit 1 
fi 
+0

也許'/ bin/sh'與'/ bin/bash'不一樣,'sh'不知道怎麼做'$()'。試試'#!/ bin/bash'。 – meuh

+0

我試過sh和bash ...沒有變化 –

+0

我不知道這個問題是否重要,但gphoto2是一個命令行應用程序。爭論 - 總結讓我看到了一大堆的價值觀。 –

回答

1

有你的shell腳本的幾個問題。讓我們一起糾正並改進。

#!/bin/sh 

file="test.txt" 
[ -f "$file" ] && rm -f "$file" 

# you want to store the output of gphoto2 in a variable 
# var=$(gphoto2 --summary) 
# problem 1: what if PATH environment variable is wrong (i.e. gphoto2 not accessible)? 
# problem 2: what if gphoto2 outputs to stderr? 
# it's better first to: 
if ! type gphoto2 > /dev/null 2>&1; then 
    echo "gphoto2 not found!" >&2 
    exit 1 
fi 
# Why using var?... 
gphoto2 --summary > "$file" 2>&1 
# if you insert any echo here, you will alter $? 
if [ $? -eq 0 ]; then 
    echo "Successfully created file" 
    exit 0 
else 
    echo "Could not create file" >&2 
    exit 1 
fi 
+0

感謝您的建議。我需要做一點挖掘才能完全理解,但你推薦的東西似乎有意義。當它從終端運行時,它的工作方式應該如此。當我從處理中運行它退出不返回它只是返回「完成」....奇怪 –

+0

我站在糾正。 「完成」來自於我今天上午添加的其他內容以進一步排除故障。這也不起作用 –

+0

如果更正的shell腳本不起作用,則必須在java域中調試問題。 –