我有以下bash脚本:
#!/bin/bash
while getopts "1:2:3:4:" arg; do
case "$arg" in
1)
fileWithSpeeds=$OPTARG
;;
2)
titleOfGraph=$OPTARG
;;
3)
lowestHP=$OPTARG
;;
4)
highestHP=$OPTARG
;;
esac
done
./myPlotter.R $fileWithSpeeds $titleOfGraph $lowestHP $highestHP
基本上,myPlotter.R
根据给定文件中的数据创建一个图(详细信息对于此问题并不重要)。在以下方式在命令行中调用时:
./myPlotter.R myFile "My Title" 30 34
脚本运行正常(不要注意myFile
,30,34;它们只是其他参数,但对于这个问题并不重要。我把它留在那里以便这个问题以防万一)。但是,从bash脚本调用时,如:
./bashPlot.sh -1 myFile -2 "My Title" -3 30 -4 34
我收到一条错误消息(args [3]中的错误:args [4],"强制引入的NAs"如果有帮助的话)。运行时:
echo ./myPlotter.R $fileWithSpeeds $titleOfGraph $lowestHP $highestHP
我注意到它看起来像以下
./myPlotter.R myFile My Title 30 34
这意味着当它不应该被标记为两个参数('我的'和#39;标题')。所以我决定将这条线修改为
./myPlotter.R $fileWithSpeeds \"$titleOfGraph\" $lowestHP $highestHP
并且该行的echo
给出了:
./myPlotter.R myFile "My Title" 30 34
但我仍然以同样的错误结束。我的猜测是标题仍然是两个参数('"''''"标题')。有没有办法来解决这个问题?如果有帮助,这是R脚本:
#!/usr/bin/env Rscript
# the arguments come in this way:
# args[1] is a file containing the maximum speeds of different cars (one per line)
# args[2] is the title that the plot will have
# args[3] contains the horsepower of the engine of the first car in args[1] (the lowest)
# args[4] contains the horsepower of the engine of the last car in args[1] (the highest)
# NOTE1: the speeds in args[1] must be listed starting from the car
# with the lowest horsepower to the car with the highest horsepower
# NOTE2: in args[1], a car must differ from the next one by 1 horsepower, i.e., if
# there are 5 speeds, and the horsepower of the first car in the file is 30, then the
# the horsepower of the second one must be 31, the third one 32, .... the fifth one must
# be 34.
args<-commandArgs(TRUE)
# creating the vector with the horsepower of each car
horsepowers = numeric()
for (i in args[3]:args[4]) {
horsepowers = c(horsepowers,i)
}
# reading file with speeds and getting vector with speeds
speeds <- read.csv(file=args[1],head=FALSE,sep="\n")$V1
# creating plot with speeds in previous vector
outputTitle = gsub(" ","", args[2] , fixed=TRUE)
pdf(paste(outputTitle, ".pdf", sep = ""))
plot(horsepowers, speeds, type="o", col="red", xlab="horsepowers", ylab="speeds")
# giving a title to the plot
title(main=args[2], col.main="Black")
答案 0 :(得分:2)
如果使用
调试脚本bash -x bashplot.sh .... arguments....
你将能够发现发生了什么。
到处使用引号,所以:
fileWithSpeeds="$OPTARG" #... and such
和
./myPlotter.R "$fileWithSpeeds" "$titleOfGraph" "$lowestHP" "$highestHP"
答案 1 :(得分:0)
更改
./myPlotter.R $fileWithSpeeds \"$titleOfGraph\" $lowestHP $highestHP
到
./myPlotter.R $fileWithSpeeds "$titleOfGraph" $lowestHP $highestHP
修复了问题。这只是我的一个小错误。