我有一个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 :(得分: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