LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Question about conditional statements. (https://www.linuxquestions.org/questions/linux-newbie-8/question-about-conditional-statements-4175456986/)

jason13131414 04-05-2013 11:22 AM

Question about conditional statements.
 
Hello everyone!

I am wondering if you can declare a variable inside a conditional statement, and then use that variable out side of the conditional statement.

Thank you!

johnsfine 04-05-2013 12:21 PM

What programming language?

In C++ you cannot do that.

jason13131414 04-05-2013 01:36 PM

Thanks for the reply.

Shell script.

rknichols 04-05-2013 03:21 PM

For bash the answer is basically "yes", but if a block of commands is executed in a subshell, then changes to variables in that block are not communicated back to the parent shell. A parenthesized list explicitly forces execution to a subshell. Commands run in the background are also done in a separate process. A block of commands with its input or output directed through a pipeline also causes those commands to be executed in a subshell, and this is a frequent cause of problems in shell scripts.
Code:

N=0
echo hello world | {
    cat
    N=42  # This will not be seen in the parent shell
}
echo $N    # N still seen as 0 here

The code within an "if ... then ... fi" construct is also a block that could have its I/O pipelined, though doing so is pretty uncommon:
Code:

N=0
echo testing | if [[ $N == 0 ]]; then
    echo "I am here"
    cat
    N=22
fi
echo $N    # Still seen as 0

Without the pipeline, and even with simple (albeit unusual) redirection, the setting of N does occur in the main shell:
Code:

N=0
if [[ $N == 0 ]]; then
    echo "I am here"
    head
    N=55
fi </etc/profile
echo $N    # Has value 55


jason13131414 04-05-2013 04:18 PM

Thank you for the response!!! Solved my problem!!!


All times are GMT -5. The time now is 05:33 PM.