bash: Execute a string as a command

爱⌒轻易说出口 提交于 2019-12-25 16:56:19

问题


See my previous question on assembling a specific string here.

I was given an answer to that question, but unfortunately the information didn't actually help me accomplish what I was trying to achieve.

Using the info from that post, I have been able to assemble the following set of strings: gnuplot -e "filename='output_N.csv'" 'plot.p' where N is replaced by the string representation of an integer.

The following loop will explain: (Actually, there is probably a better way of doing this loop, which you may want to point out - hopefully the following code won't upset too many people...)

  1 #!/bin/bash
  2 n=0
  3 for f in output_*.csv
  4 do
  5     FILE="\"filename='output_"$n".csv'\""
  6     SCRIPT="'plot.p'"
  7     COMMAND="gnuplot -e $FILE $SCRIPT"
  8     $COMMAND
  9     n=$(($n+1))
 10 done

Unfortunately this didn't work... gnuplot does run, but gives the following error message:

"filename='output_0.csv'"
^
line 0: invalid command


"filename='output_1.csv'"
^
line 0: invalid command


"filename='output_2.csv'"
^
line 0: invalid command


"filename='output_3.csv'"
^
line 0: invalid command

...

So, as I said before, I'm no expert in bash. My guess is that something isn't being interpreted correctly - either something is being interpreted as a string where it shouldn't or it is not being interpreted as a string where it should? (Just a guess?)

How can I fix this problem?

The first few (relevant) line of my gnuplot script are the following:

(Note the use of the variable filename which was entered as a command line argument. See this link.)

30 fit f(x) filename using 1:4:9 via b,c,e
31 
32 plot filename every N_STEPS using 1:4:9 with yerrorbars title "RK45 Data", f(x) title "Landau Model"

回答1:


Easy fix - I made a mistake with the quotation marks. ("")

Essentially, the only reason why the quotation marks " and " are required around the text filename='output_"$n".csv' is so that this string is interpreted correctly by bash, before executing the command! So indeed it is correct that the program runs when the command gnuplot -e "filename='output_0.csv'" 'plot.p' is entered into the terminal directly, but the quotation marks are NOT required when assembling the string beforehand. (This is a bit difficult to explain, but hopefully it is clear in your mind the difference between the 2.)

So the corrected version of the above code is:

  1 #!/bin/bash
  2 n=0
  3 for f in output_*.csv
  4 do
  5     FILE="filename='output_"$n".csv'"
  6     SCRIPT='plot.p'
  7     COMMAND="gnuplot -e $FILE $SCRIPT"
  8     $COMMAND
  9     n=$(($n+1))
 10 done

That is now corrected and working. Note the removal of the escaped double quotes.



来源:https://stackoverflow.com/questions/30870500/bash-execute-a-string-as-a-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!