I have one config and one main bash script files. Config file has variables assigned with values whereas, the main file wants to access them. Below are my files,
config.sh
#!/bin/bash
username=abc
password=abc
hosts=(192.168.110.164);
walletname=varsh
main.sh
#!/bin/bash
source ~/shell/config.sh
echo "$username"
echo "$walletname"
start_block(){
echo "$username"
echo "$walletname"
}
SCRIPT="$(declare -f); start_block"
for i in ${!hosts[*]} ; do
printf "\t=========== Logging in ${hosts[i]} ===========\n\n"
SCR=${SCRIPT/PASSWORD/${password}}
sshpass -p ${password} ssh -l ${username} ${hosts[i]} "${SCR}"
done
$username and $walletname can be accessed from outside of the start_block function but not from inside the function. The echo from the function start_block gives empty results. I tried using export before variable names in config. How can I access these variables?
Edit:
I want to login to another host using the username password, create some files, run installation and other commands using config file variables. And there could be many variables in the config.
start_blockis being executed anywhere in the scriptSCRIPT="$(declare -f); start_block"ftn_1() {...}; ftn_2() {...}; ...) and then you try to search/replace all instances of PASSWORD with the variables in the config. Note: currently,SCRwill only replace the first instance, to replace all, you'll needSCR=${SCRIPT//PASSWORD/${password}}(two slashes). But I don't know if that resolves your issue.$SCR(or$SCRIPTfor that matter). (As already mentioned.) There might be a way to accomplish what you're trying to do here, but it seems like a really fragile way to implement variables in a shell script (i.e, global search & replace based on pattern). (rest of comment deleted, doesn't work).sshandscript. Logging in${!hosts[*]}is not the issue.start_blockfunction is also getting executed (tested with printing some string inside function).