-2

I have a bash script which sets environment variables and then creates another (child?) bash process in which those variables are set.

I'd like to execute a command inside that new bash script, which is within the scope of the newly created environment variables. I know that I can call bash and pass in another existing .sh file, however I need to pass in a string which can be dynamically generated.

Is this possible?

#!/bin/bash
# ....
export AWS_ACCESS_KEY_ID=$AccessKeyId
export AWS_SECRET_ACCESS_KEY=$SecretAcessKey
# ...

# This line fails
bash  <$(echo "aws sts get-caller-identity")

Thanks very much.

Damien Sawyer
  • 5,323
  • 3
  • 44
  • 56
  • Does this answer your question? [How to execute new bash command inside shell script file?](https://stackoverflow.com/questions/66849823/how-to-execute-new-bash-command-inside-shell-script-file) – Deepan Aug 14 '22 at 13:44
  • no, not really. That is executing commands in another file. I want to specify what to execute via a string which can be generated from previous steps in the script. I'll reword the question. – Damien Sawyer Aug 15 '22 at 01:47

1 Answers1

1

You can use a here document to accomplish this effect.

#!/bin/bash
export ENV_VAR="hello"
# some dynamically made script that uses the environment variable 
dynamic_script="echo \$ENV_VAR" 

# notice if you were to echo this here, it would have the dollar sign
# echo $dynamic_script

bash<<HERE
$dynamic_script
HERE

Documentation: https://tldp.org/LDP/abs/html/here-docs.html

Though I don't see why you couldn't simply output the script to a file and run that.

echo "$dynamic_script" > my_child.sh
chmod +x my_child.sh
./my_child.sh
metzkorn
  • 335
  • 2
  • 8
  • Thank you - that's perfect. I guess that I could just write a file, but don't you find it cleaner not to? Why write a temp file when you don't need to? – Damien Sawyer Aug 15 '22 at 04:37
  • That's true. I can understand the appeal of wanting everything contained. – metzkorn Aug 15 '22 at 04:59