Home > front end >  Bash: execute a string as if it was a script and pass parameters
Bash: execute a string as if it was a script and pass parameters

Time:02-02

If I have a bash script stored in a file I can execute it as follows:

./path-to-script.sh param1 param2 param3

now if I have that same script stored in a variable:

script="$(cat ./path-to-script.sh)"

How can I execute it with those same parameters?

(For context - I'm running the script on a remote computer, and have to copy paste it into the command to send. I could echo it into a file in the remote computer and execute that, but if I can avoid touching the file system that would be better).

CodePudding user response:

Like this:

bash -c "$script" my_script param1 param2 param3

my_script is gonna be the name of your script and appear in error messages. For example:

$ bash -c 'echo ${1bad_var}' my_script
my_script: line 1: ${1bad_var}: bad substitution
  •  Tags:  
  • bash
  • Related