Home > Software engineering >  How to Pass Value from One Shell Block to Another Shell Block or assign that value to the Variable o
How to Pass Value from One Shell Block to Another Shell Block or assign that value to the Variable o

Time:09-19

script{

    println("Starting TEST")

    //Declaring Variable var value in the Below Shell Block
    sh"""
        echo "This is Test"
        var=10
        echo "This is Test Value \$var"
    """

    //Trying to Print the var Value from above Block
    sh"""
        echo "This is Other Block"
        echo "This is Test Value \$var"
    """

    //Copying the value from Shell Script Variable to Groovy Script
    def scriptVar=sh(script:"\$var ")
}

In the above code Im trying to print the value of a shell block and use the same value to assign the value in next block but echo will just show blank message after printing value in 2nd block

CodePudding user response:

You can simply write the value to a file and then read it from there. Check the following.

script{
        println("Starting TEST")
        //Declaring Variable var value in the Below Shell Block
        sh"""
            echo "This is Test"
            var=10
            echo \$var > varOut
            echo "This is Test Value \$var"
        """
    
        //Trying to Print the var Value from above Block
        sh"""
            echo "This is Other Block"
            var=\$(cat varOut)
            echo "This is Test Value \$var"
        """

        // Assign the value to a variable
        def var = readFile(file: "varOut")
        echo "Var = $var"
}
  • Related