ico*_*ast 13 shell bash io-redirection subshell
我编写了一个快速而肮脏的脚本来计时来自 Web 服务的一些报告:
BASE_URL='http://example.com/json/webservice/'
FIRST=1
FINAL=10000
for report_code in $(seq 1 $FINAL); do
(time -p response=$(curl --write-out %{http_code} --silent -O ${BASE_URL}/${report_code}) ) 2> ${report_code}.time
echo $response # <------- this is out of scope! How do I fix that?
if [[ $response = '404' ]]; then
echo "Deleting report # ${report_code}!"
rm ${report_code}
else
echo "${report_code} seems to be good!"
fi
done
Run Code Online (Sandbox Code Playgroud)
我需要将time
命令包装在一个子 shell 中,以便我可以重定向它的输出,但这使得$response
父 shell的值不可用。我该如何解决这个问题?
Gil*_*il' 12
您不能将变量的值从子 shell 带到其父级,除非进行一些容易出错的编组和繁琐的通信。
幸运的是,这里不需要子shell。重定向只需要命令分组用{ … }
,而不是一个子shell。
{ time -p response=$(curl --write-out '%{http_code}' --silent -O "${BASE_URL}/${report_code}"); } 2> "${report_code}.time"
Run Code Online (Sandbox Code Playgroud)
(不要忘记变量替换周围的双引号。)