Varsh
Varsh

Reputation: 465

Cannot access config file variables in bash script function

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.

Upvotes: 0

Views: 625

Answers (2)

HappyFace
HappyFace

Reputation: 4133

Your variables are not sent to the remote host. You can forcibly inline them, like you do the functions:

SCRIPT="$(env) ; $(declare -f) ; start_block"

I'd, however, recommend just inlining the config directly:

SCRIPT="$(cat ~/shell/config.sh) ; $(declare -f); start_block"

Upvotes: 2

user1934428
user1934428

Reputation: 22301

The function is executed, when you do a ssh -l ${username} ${hosts[i]} "${SCR}". Hence it is executed in a separate process, most likely even on a different host. Of course you don't see your shell variables over there. Actually it is surprising that on the remote side, start_block does not give raise to a command not found error, since the function also exists in your local process only.

As for the variables, you could turn them into environment variables (by using the export command) and use the SendEnv and AcceptEnv options in your ssh configuration file, as explained for instance here.

Upvotes: 1

Related Questions