
Bash에서 명령 출력을 캡처하는 데 몇 가지 문제가 있습니다.
C 프로그램을 테스트하기 위한 Bash 스크립트가 있습니다...
bufsize=1
while [ $bufsize -le 16384 ]
do
runtime=$(/usr/bin/time -f "%e" -o /dev/tty \
./raw_copy $bufsize ./country_vaccinations.csv raw_copy.out)
echo "Runtime for array with $bufsize slots was $runtime."
bufsize=$(( $bufsize * 2 ))
done
raw_copy
(프로그램이 사용할 수 있는 메모리 양을 기준으로 우리가 작성하는 프로그램이 얼마나 빨리 파일을 복사할 수 있는지 테스트합니다. 숙제입니다.)
time
나는 명령의 출력을 이라는 변수에 캡처하는 몇 가지 다른 변형을 시도했습니다 runtime
. 예를 들어 runtime=$(stuff)
위에서 언급한 대로 runtime="$(stuff)"
명령에서 따옴표도 변경합니다 echo
. 그러나 나는 내가 찾고 있는 것을 확실히 얻을 수 없습니다. 내가 계속 얻는 결과는 다음과 같습니다.
$ ./test4.sh
0.60
Runtime for array with 1 slots was .
0.30
Runtime for array with 2 slots was .
0.15
Runtime for array with 4 slots was .
0.07
Runtime for array with 8 slots was .
0.04
Runtime for array with 16 slots was .
0.01
Runtime for array with 32 slots was .
0.01
Runtime for array with 64 slots was .
(et cetera)
아시다시피 저는 다음과 같은 것을 찾고 있습니다.
$ ./test4.sh
Runtime for array with 1 slots was 0.60.
Runtime for array with 2 slots was 0.30.
(et cetera)
누군가가 나를 도울 수 있는지 확인하고 싶었습니다. (그래서 본질적으로 time
명령의 출력을 그냥 인쇄하는 대신 변수에 저장하는 방법을 알아내는 데 어려움을 겪고 있습니다 .)
답변1
기본적으로 적어도 time
내 Debian은 stderr로 출력하는데 이는 명령 대체에 사용하기에 좋지 않습니다. 명령에서 /dev/tty
터미널에 직접 인쇄하도록 지시하더라도 이 역시 작동하지 않습니다.
다음 주소로 인쇄하라고 지시하세요 /dev/stdout
:
t=$(/usr/bin/time -f "%e" -o /dev/stdout sleep 1)
echo "that took $t s"
또는 셸에서 리디렉션합니다.
t=$(/usr/bin/time -f "%e" sleep 1 2>&1)