4

I have local bash script which is used to invoke a bash script in the remote server and get some reports from remote server.

The way I call this script currently in local_script.sh is:

ssh remoteuse@ip "/bin/bash remote_script.sh"

Now, I want to set a date variable in local_script.sh file and variable needs to available in remote_script.sh files also.

Please give some ideas.

EDIT:

Please see my test script:

[user@localserver]$ ssh remoteusr@ip "/bin/bash remote_script.sh $test_var"

And my remote script:

[user@remoteserver]$ cat remote_script.sh
#!/bin/bash
echo $test_var > test_var.log

But test_var.log file on remote server is empty after running the script

1
  • I have noticed you commented on other solutions whether they helped or not. Please take a look at my answer as well, any feedback is welcome :) Commented Aug 21, 2018 at 12:40

2 Answers 2

1

The remote server doesn't know you local variables, you can only pass the value of the variable from local to remote with an extra argument at the ssh line:

ssh remoteuse@ip "/bin/bash remote_script.sh $variable"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for quick reply. I tried the same and not working for me. I have added my test script in post. Please let me know
1

You have to add the variable to the environment of the executed command. That can be done with the var=value cmd syntax.

But since the line you pass to ssh will be evaluated on the remote server, you must ensure the variable is in a format that is reusable as shell input. Two ways come to mind depending on your version of bash:

  1. With bash 4.4 or newer, you can use the Q operator in ${parameter@operator}:

    local script:

    foo="abc'def  \"123\"  *"
    ssh remoteuse@ip "foo=${foo@Q} /bin/bash remote.sh"
    

    remote script:

    printf '<%s>\n' "$foo"
    

    output:

    $ ./local_script.sh
    <abc'def  "123"  *>
    
  2. If you don't have bash 4.4 or newer, you can use the %q directive to printf:

    ssh remoteuse@ip "foo=$(printf '%q' "$foo") /bin/bash remote.sh"
    

Comments

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.