0

I have something like this...

I have three files. two files which contains same variables but different values and a third file which executes commands such as cd to a certain place

my third file is called init.sh and looks something like

###############
# works perfectly if I do it this way
source db/abc.sh  # changes variable
source db/commands.sh

source db/def.sh  # changes variable
source db/commands.sh


###############
# does not work
RUN_COMMANDS=$(source db/commands.sh)

source db/1107556.sh  # changes variable
${RUN_COMMANDS}  # this does not run

source db/kunyuan.sh # changes variable
${RUN_COMMANDS}  # this runs

Reason I am doing this is so I can change the variables then run the same commands since the commands are the same but just different values for the variable.

Hopefully I am not doing anything stupid to think this way of using bash.

Thanks in advance for any help or suggestions.

1 Answer 1

3

This:

RUN_COMMANDS=$(source db/commands.sh)

means "run the command source db/commands.sh, and store its output (= everything it printed to standard output) in the variable RUN_COMMANDS".

Instead, you seem to want:

RUN_COMMANDS=(source db/commands.sh)     # note -- no '$'

source db/1107556.sh
"${RUN_COMMANDS[@]}"

source db/kunyuan.sh
"${RUN_COMMANDS[@]}"

which sets RUN_COMMANDS to an array containing source and db/commands.sh, and then runs that array as a command (which is equivalent to running the command source db/commands.sh).

That said, you might want to consider writing a shell function:

function run-db-commands() {
    source "$1" && source db/commands.sh
}

run-db-commands db/1107556.sh
run-db-commands db/kunyuan.sh
Sign up to request clarification or add additional context in comments.

1 Comment

ah! got it, and really thanks for the suggestions, the shell function you suggested would be way better and cleaner to look at too. Thanks a lot~!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.