Is there a way to allow a background job in bash to modify variables? for ex:
[bash]# a=1
[bash]# a=2 &
[1] 14533
[bash]# echo $a
1
I开发者_如何学Python'd like the value of a to be 2 not 1
Variables can't be sent back to a parent process from a child, so what you're trying to do is impossible. It's the same reason that cd
has to be a shell builtin rather than an executable in its own right. If it were an executable, it would run, change the directory, and then exit, leaving you back in the shell which hasn't had its directory changed.
A child process can't affect his parent's environment, but if your background process ends after the evaluation you can "pass" the value as an exit code. The parent can catch it with the wait
command. Here is an example of a background process returning a variable incremented by one:
etuardu@subranu:~$ a=1
etuardu@subranu:~$ (exit $[ $a + 1 ]) &
[1] 7486
etuardu@subranu:~$ wait $!; a=$?
[1]+ Exit 2 ( exit $[ $a + 1 ] )
etuardu@subranu:~$ echo $a
2
As Carl explained quite well, it is impossible.
An example:
#!/bin/bash
a=1
for i in 1 2 3 4 5 6 7 8 9 10
do
let a=a+1 ;echo "Child value $a"
done &
sleep 2
echo "Parent value $a"
Output would show child with value 1-10, and then parent with old value of 1.
-> a=1
-> a=2; exit &
-> echo $a
2
精彩评论