bash functions & command substitution

Need help with C, C++, perl, python, etc?

bash functions & command substitution

Postby vved » 2007-04-09 17:53

I have 3 questions about the following bash script.
1. Is it legal to use a function in command substitution?
2. Why ttt is not assigned outside the function? Because it is called in subshell?
3. Then why the initial value is visible in subshell?

set -x
ttt="false"

Func()
{
if [ "$ttt" = "true" ]
then
echo $ttt
else
echo $ttt
ttt="true"
fi
}

echo ttt=$ttt
aaa=$(Func)

echo aaa=$aaa
echo ttt=$ttt
aaa=$(Func)

echo aaa=$aaa
echo ttt=$ttt
-----------------
output
-----------------
++ ttt=false
++ echo ttt=false
ttt=false
+++ Func
+++ '[' false = true ']'
+++ echo false
+++ ttt=true
++ aaa=false
++ echo aaa=false
aaa=false
++ echo ttt=false
ttt=false
+++ Func
+++ '[' false = true ']'
+++ echo false
+++ ttt=true
++ aaa=false
++ echo aaa=false
aaa=false
++ echo ttt=false
ttt=false
vved
 

bash functions & command substitution

Postby guest1 » 2007-04-10 01:45

From the Advanced Bash-Scripting Guide ( here ) : "Variables in a subshell are not visible outside the block of code in the subshell. They are not accessible to the parent process, to the shell that launched the subshell. These are, in effect, local variables."

Try running example 20-1.
guest1
 


Return to Programming

Who is online

Users browsing this forum: No registered users and 3 guests

fashionable