1

I want to be able to issue shell commands from a gnuplot script, such as setting a variable, but it appears that the system command spawns a new shell instance as opposed to issuing commands to the shell instance which is running the gnuplot script. See the following script where the first line allows assignment of $foo, but the second line cannot access that variable. In this case, $foo is assigned as an arbitrary string as opposed to a reference to the directory, hence the \"

#!/usr/bin/gnuplot -p
system "export foo=\"$HOME/path/to/dir\";echo $foo"
system "echo $foo"
set datafile separator "\t"
#plot "`echo $foo`/bar.dat" using 2:3
plot "<( sed '5p' $foo/bar.dat )" using 2:3
T. Zack Crawford
  • 232
  • 2
  • 10

1 Answers1

3

You are right: Each system command issues a brand new shell, so the variable set with system "foo=bar" is gone when Gnuplot goes to the following line.

A very convenient approach in your case is to use here-docs.

foo="$HOME/path/to/dir"

gnuplot -p<<EOF set datafile separator "\t" plot '<(sed "5p" "$foo"/bar.dat)' EOF

Some notes about the script:

  • sed "5p" file means that all the lines of the file will be plotted, but the 5th line will be duplicated. If you meant to only plot the 5th line, use sed -n "5p" file

  • This calls Gnuplot but is still a shell script, therefore it is better to always quote variables (such as "$foo") to prevent word splitting.

Quasímodo
  • 18,865
  • 4
  • 36
  • 73
  • 1
    Thank you! The sed command was just to illustrate how this may be useful, I actually meant it to be sed '5q'. On a side note, the <( ) part is of the form of process substitution, but I think this may actually be a gnuplot construct in this case. Try replacing the shebang with #!/bin/dash (if installed) in your script and executing. Now try sed "5p" <( cat "$foo"/bar.dat ) in each dash and bash and see what happens. – T. Zack Crawford Sep 09 '20 at 17:22
  • 1
    @T.ZackCrawford You are welcome! And you are quite right, that is not process substitution but inner workings of Gnuplot, as I have found in the PDF manual. It is so nice that here in Stack we also learn by answering! – Quasímodo Sep 09 '20 at 21:21