I wrote a script:
Old script:
var="$(sleep 5 && echo "Linux is...")" &
sleep 5
echo $var
New script:
var="$(cat file | grep Succeeded && kilall cat)" & killer1=$!
(sleep 60; kill $killer1) & killer2=$!
fg 1
kill $killer2
e开发者_如何学Gocho $var
Cat file works all the time. Should return "... \n Succeeded \n ...". Echo empty always returns. Is there a solution? I want to necessarily result in a variable.
When you terminate a command by &
, the shell executes the command in a subshell. var
is set in the subshell, not the original process.
If you run it on the background using &, it is in separate process, so you no more share variables. You need to use IPC (interprocess comunication) to assure this. Easiest IPC to use is a pipe:
{ sleep 2 && echo 'Linux is ...' ; } |
{
echo 'doing something here in the meantime...'
sleep 1
read var
echo $var
}
Remove the &
from the assignment of var (line 1 in your script).
精彩评论