-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.

2
  • Does this answer your question? How to execute new bash command inside shell script file? Commented Aug 14, 2022 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. Commented Aug 15, 2022 at 1:47

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
That's true. I can understand the appeal of wanting everything contained.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.