How to pass command line argument to gnuplot?
I want to use gnuplot to draw figure from data file, say foo.data. Currently, I hardcoded the data file name in the command file, say foo.plt, and run command gnuplot foo.plg
to plot data. However, I want to pass the data file name as a command argument, e.g. running command gnuplot foo.plg foo.data
. How to parse the command line arguments in gnuplot script file? Thanks.
You can input variables via switch -e
$ gnuplot -e "filename='foo.data'" foo.plg
In foo.plg you can then use that variable
$ cat foo.plg
plot filename
pause -1
To make "foo.plg" a bit more generic, use a conditional:
if (!exists("filename")) filename='default.dat'
plot filename
pause -1
Note that -e
has to precede the filename otherwise the file runs before the -e
statements. In particular, running a shebang gnuplot #!/usr/bin/env gnuplot
with ./foo.plg -e ...
CLI arguments will ignore use the arguments provided.
You can pass arguments to a gnuplot script since version 5.0, with the flag -c
. These arguments are accessed through the variables ARG0
to ARG9
, ARG0
being the script, and ARG1
to ARG9
string variables. The number of arguments is given by ARGC
.
For example, the following script ("script.gp")
#!/usr/local/bin/gnuplot --persist
THIRD=ARG3
print "script name : ", ARG0
print "first argument : ", ARG1
print "third argument : ", THIRD
print "number of arguments: ", ARGC
can be called as:
$ gnuplot -c script.gp one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
or within gnuplot as
gnuplot> call 'script.gp' one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
In gnuplot 4.6.6 and earlier, there exists a call
mechanism with a different (now deprecated) syntax. The arguments are accessed through $#
, $0
,...,$9
. For example, the same script above looks like:
#!/usr/bin/gnuplot --persist
THIRD="$2"
print "first argument : ", "$0"
print "second argument : ", "$1"
print "third argument : ", THIRD
print "number of arguments: ", "$#"
and it is called within gnuplot as (remember, version <4.6.6)
gnuplot> call 'script4.gp' one two three four five
first argument : one
second argument : two
third argument : three
number of arguments: 5
Notice there is no variable for the script name, so $0
is the first argument, and the variables are called within quotes. There is no way to use this directly from the command line, only through tricks as the one suggested by @con-fu-se.