[Ethereum] Executing custom JavaScript Snippets through Non-Interactive console (geth –exec)

consolego-ethereumjavascriptprivate-blockchainweb3js

I have a JavaScript snippet to get the latest transaction to/from an account. After starting the geth instance, I did this in the interactive JS console:

jsFunction is a function in filename.js

>loadScript("/path/to/file/filename.js")
true
>jsFunction(<parameters>)
<Returns the results as expected>

But when I try to do the same using the Non-interactive mode, it fails:

$ geth --exec 'loadScript("/path/to/file/filename.js")' attach ipc:/path/to/ipc
true
$ geth --exec 'jsFunction(<parameters>)' attach ipc:/path/to/ipc
ReferenceError: 'jsFunction' is not defined
    at <anonymous>:1:1

I ran the same command (geth –exec) with normal web3.js functions like eth.getTransaction, eth.getBlock and it works fine. I don't understand what's wrong with executing custom scripts. Does geth client support this functionality? Am I missing something?

P.S: I am running a private blockchain but didn't mention –datadir, –networkid, and –genesis etc. in the above commands for readability.

Best Answer

Each geth exec start one interpreter. So if you define a function into the first, it is not available on the second... Please merge them into one exec:

To sum up:

 geth --exec 'loadScript("/path/to/file/filename.js"); jsFunction(...)' attach

This also worked:

geth --exec "loadscript(\"/path/to/file/filename.js\");jsFunction(<params>)" attach ipc:/path/to/ipc
Related Topic