Bash – How to execute shell scrips without creating files

bashshshellshell-scripting

How is it possible to execute a shell script without creating a file? For example assume I have the following script (testscript):

#!/bin/bash
function run_free() {
   free -m
}

run_free

I then of course can execute this with: sh testscript

I want to ovoid creating a file though. I tried:


sh echo '#!/bin/bash
function run_free() {
free -m
}
run_free'

Which did not work. Any ideas?

Best Answer

Most interpreters have a parameter to specify some code to execute. You can use this to invoke a specific interpreter and provide the code. For example:

bash -c 'function run_free() { free -m; }; run_free'

(Note that you need some semicolons in there since you don't have newlines.)

perl uses -e, and python uses -c.