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
  • 3
    This is the normal behavior of system in various programming languages. – Bodo Sep 9 at 16:35

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.


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

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.

| improve this answer | |
  • 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 9 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 9 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.