我有2个bash文件,文件a.sh和文件b.sh。
文件a.sh
的内容# !/bin/bash
(/root/b.sh) & # <--- must be run in the background!!!
sleep 1
echo "--${VAR}--"
文件b.sh
的内容# !/bin/bash
VAR=100
运行脚本/root/a.sh,结果是:----
为什么不是结果: - 100 - ?
答案 0 :(得分:1)
<强> a.sh 强>
# !/bin/bash
ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SCRIPT_FILE="$ROOT_DIR/b.sh"
$SHELL $SCRIPT_FILE &
SCRIPT_PID=$!
TEMP_FILE="/tmp/$SCRIPT_PID.data"
# kill child process on exit
trap cleanup EXIT INT TERM
cleanup() {
kill $SCRIPT_PID
exit $?
}
# wait child process to put data
waitdata() {
while [ ! -f $TEMP_FILE ]
do
sleep 1
done
}
# main loop
while :
do
waitdata
VAR=$(cat $TEMP_FILE)
echo $VAR
sleep 2
done
<强> b.sh 强>
#!/bin/bash
# my pid
TEMP_FILE="/tmp/$$.data"
# trap (control-c, kill, etc)
trap cleanup EXIT INT TERM
cleanup() {
rm -f $TEMP_FILE
exit $?
}
# main loop
while :
do
VAR=$(date)
#echo $VAR
echo $VAR > $TEMP_FILE
sleep 2
done