How to get either the last line of output or the exit codeexit code of the command **before** last?How to delete a directory automatically when an executable is killedExecute code on remote machine and copy the results backBash Executing Script from within Script Causes Echo and Read Issuesexit code of the command **before** last?Grep Command execution within a loop gives error`tail -f` consumes last line partially, doesn't care about newlines or nulHow to redirect error info of executable C program to stdout? (MAC OS X)bash echo the command line executed at the command line itself (not in a script)Teaching assistant bash script to automate the process of finding, compiling, and running .java filesSlicing the output of grep in bash
Could the museum Saturn V's be refitted for one more flight?
In Bayesian inference, why are some terms dropped from the posterior predictive?
How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?
What do you call someone who asks many questions?
Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?
What's the meaning of "Sollensaussagen"?
Why was the shrink from 8″ made only to 5.25″ and not smaller (4″ or less)
What is the most common color to indicate the input-field is disabled?
How dangerous is XSS
Why was Sir Cadogan fired?
Finitely generated matrix groups whose eigenvalues are all algebraic
Car headlights in a world without electricity
How could indestructible materials be used in power generation?
Why are UK visa biometrics appointments suspended at USCIS Application Support Centers?
Getting extremely large arrows with tikzcd
What is the opposite of "eschatology"?
Are British MPs missing the point, with these 'Indicative Votes'?
Unlock My Phone! February 2018
How badly should I try to prevent a user from XSSing themselves?
Send out email when Apex Queueable fails and test it
files created then deleted at every second in tmp directory
What historical events would have to change in order to make 19th century "steampunk" technology possible?
Why is the sentence "Das ist eine Nase" correct?
Sums of two squares in arithmetic progressions
How to get either the last line of output or the exit code
exit code of the command **before** last?How to delete a directory automatically when an executable is killedExecute code on remote machine and copy the results backBash Executing Script from within Script Causes Echo and Read Issuesexit code of the command **before** last?Grep Command execution within a loop gives error`tail -f` consumes last line partially, doesn't care about newlines or nulHow to redirect error info of executable C program to stdout? (MAC OS X)bash echo the command line executed at the command line itself (not in a script)Teaching assistant bash script to automate the process of finding, compiling, and running .java filesSlicing the output of grep in bash
I am writing an automated homework grader in bash. The grader compiles a program and runs it. If the program fails to compile or fails to run (e.g. due to a segmentation fault) the grade should be a fixed small number, e.g. 5. Otherwise, the grade is the last line output by the program.
To get the last line, I can do:
grade=$( ./a.out | tail -1 )
But this always gives an exit code of 0, even if a.out fails to run (e.g. not found), so I cannot tell whether the program failed to exist.
Another option is to use a temporary file:
./a.out > temp
if [ $? -ne 0 ]
then
grade=0
else
grade=$( tail -1 temp )
fi
However, this might be problematic if there are many different processes doing the same simultaneously. Even with one process, it is wasteful to keep all output in a file (the output might be large) when I only need the last line.
Is there a solution that does not use a temporary file?
bash scripting
|
show 3 more comments
I am writing an automated homework grader in bash. The grader compiles a program and runs it. If the program fails to compile or fails to run (e.g. due to a segmentation fault) the grade should be a fixed small number, e.g. 5. Otherwise, the grade is the last line output by the program.
To get the last line, I can do:
grade=$( ./a.out | tail -1 )
But this always gives an exit code of 0, even if a.out fails to run (e.g. not found), so I cannot tell whether the program failed to exist.
Another option is to use a temporary file:
./a.out > temp
if [ $? -ne 0 ]
then
grade=0
else
grade=$( tail -1 temp )
fi
However, this might be problematic if there are many different processes doing the same simultaneously. Even with one process, it is wasteful to keep all output in a file (the output might be large) when I only need the last line.
Is there a solution that does not use a temporary file?
bash scripting
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
1
Inbash, you can usePIPESTATUSinstead of$?:exit 13 | tail -n1; echo $PIPESTATUS[0]
– mosvy
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
1
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)
– mosvy
2 days ago
|
show 3 more comments
I am writing an automated homework grader in bash. The grader compiles a program and runs it. If the program fails to compile or fails to run (e.g. due to a segmentation fault) the grade should be a fixed small number, e.g. 5. Otherwise, the grade is the last line output by the program.
To get the last line, I can do:
grade=$( ./a.out | tail -1 )
But this always gives an exit code of 0, even if a.out fails to run (e.g. not found), so I cannot tell whether the program failed to exist.
Another option is to use a temporary file:
./a.out > temp
if [ $? -ne 0 ]
then
grade=0
else
grade=$( tail -1 temp )
fi
However, this might be problematic if there are many different processes doing the same simultaneously. Even with one process, it is wasteful to keep all output in a file (the output might be large) when I only need the last line.
Is there a solution that does not use a temporary file?
bash scripting
I am writing an automated homework grader in bash. The grader compiles a program and runs it. If the program fails to compile or fails to run (e.g. due to a segmentation fault) the grade should be a fixed small number, e.g. 5. Otherwise, the grade is the last line output by the program.
To get the last line, I can do:
grade=$( ./a.out | tail -1 )
But this always gives an exit code of 0, even if a.out fails to run (e.g. not found), so I cannot tell whether the program failed to exist.
Another option is to use a temporary file:
./a.out > temp
if [ $? -ne 0 ]
then
grade=0
else
grade=$( tail -1 temp )
fi
However, this might be problematic if there are many different processes doing the same simultaneously. Even with one process, it is wasteful to keep all output in a file (the output might be large) when I only need the last line.
Is there a solution that does not use a temporary file?
bash scripting
bash scripting
edited yesterday
Rich
369212
369212
asked 2 days ago
Erel Segal-HaleviErel Segal-Halevi
3201210
3201210
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
1
Inbash, you can usePIPESTATUSinstead of$?:exit 13 | tail -n1; echo $PIPESTATUS[0]
– mosvy
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
1
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)
– mosvy
2 days ago
|
show 3 more comments
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
1
Inbash, you can usePIPESTATUSinstead of$?:exit 13 | tail -n1; echo $PIPESTATUS[0]
– mosvy
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
1
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)
– mosvy
2 days ago
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
1
1
In
bash, you can use PIPESTATUS instead of $?: exit 13 | tail -n1; echo $PIPESTATUS[0]– mosvy
2 days ago
In
bash, you can use PIPESTATUS instead of $?: exit 13 | tail -n1; echo $PIPESTATUS[0]– mosvy
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
1
1
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:
grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)– mosvy
2 days ago
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:
grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)– mosvy
2 days ago
|
show 3 more comments
2 Answers
2
active
oldest
votes
Your problem boils down to: "I want to get the last line of output AND detect abnormal exit without using temporary files". In that case, set -o pipefail is your friend.
Here's a simple script that executes its arguments and records the last line of the output on normal exit:
#!/bin/bash
[[ -x $1 ]] ||
echo >&2 "Usage $0##*/ <PROGRAM> [ARG1] ..."
exit 1
set -o pipefail
program=$1
shift;
x=$($program "$@" | tail -1)
if [[ $? -eq 0 ]]; then
echo "Pass: $x"
else
echo "Fail: $?"
fi
I'll leave the problem of assigning a grade to you.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
grade=$( echo 0; | tail -n 1 )
This would try to execute ./a.out and then add a line with a single 0 to its output if that program exited with a non-zero exit status or failed to execute at all. The 0 would be caught by tail -n 1 and placed in $grade.
If ./a.out executed correctly and terminated with a zero exit status, the echo would not be triggered.
Remove the redirection of standard error to /dev/null if you are interested in seeing diagnostic messages related to running ./a.out.
Change the 0 to "$?" to get the exit code instead. To be able to differentiate a number from an error, you may want to use NaN instead, or some error string.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "106"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509739%2fhow-to-get-either-the-last-line-of-output-or-the-exit-code%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your problem boils down to: "I want to get the last line of output AND detect abnormal exit without using temporary files". In that case, set -o pipefail is your friend.
Here's a simple script that executes its arguments and records the last line of the output on normal exit:
#!/bin/bash
[[ -x $1 ]] ||
echo >&2 "Usage $0##*/ <PROGRAM> [ARG1] ..."
exit 1
set -o pipefail
program=$1
shift;
x=$($program "$@" | tail -1)
if [[ $? -eq 0 ]]; then
echo "Pass: $x"
else
echo "Fail: $?"
fi
I'll leave the problem of assigning a grade to you.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Your problem boils down to: "I want to get the last line of output AND detect abnormal exit without using temporary files". In that case, set -o pipefail is your friend.
Here's a simple script that executes its arguments and records the last line of the output on normal exit:
#!/bin/bash
[[ -x $1 ]] ||
echo >&2 "Usage $0##*/ <PROGRAM> [ARG1] ..."
exit 1
set -o pipefail
program=$1
shift;
x=$($program "$@" | tail -1)
if [[ $? -eq 0 ]]; then
echo "Pass: $x"
else
echo "Fail: $?"
fi
I'll leave the problem of assigning a grade to you.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Your problem boils down to: "I want to get the last line of output AND detect abnormal exit without using temporary files". In that case, set -o pipefail is your friend.
Here's a simple script that executes its arguments and records the last line of the output on normal exit:
#!/bin/bash
[[ -x $1 ]] ||
echo >&2 "Usage $0##*/ <PROGRAM> [ARG1] ..."
exit 1
set -o pipefail
program=$1
shift;
x=$($program "$@" | tail -1)
if [[ $? -eq 0 ]]; then
echo "Pass: $x"
else
echo "Fail: $?"
fi
I'll leave the problem of assigning a grade to you.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Your problem boils down to: "I want to get the last line of output AND detect abnormal exit without using temporary files". In that case, set -o pipefail is your friend.
Here's a simple script that executes its arguments and records the last line of the output on normal exit:
#!/bin/bash
[[ -x $1 ]] ||
echo >&2 "Usage $0##*/ <PROGRAM> [ARG1] ..."
exit 1
set -o pipefail
program=$1
shift;
x=$($program "$@" | tail -1)
if [[ $? -eq 0 ]]; then
echo "Pass: $x"
else
echo "Fail: $?"
fi
I'll leave the problem of assigning a grade to you.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered yesterday
Chris WilliamsChris Williams
411
411
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Chris Williams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
grade=$( echo 0; | tail -n 1 )
This would try to execute ./a.out and then add a line with a single 0 to its output if that program exited with a non-zero exit status or failed to execute at all. The 0 would be caught by tail -n 1 and placed in $grade.
If ./a.out executed correctly and terminated with a zero exit status, the echo would not be triggered.
Remove the redirection of standard error to /dev/null if you are interested in seeing diagnostic messages related to running ./a.out.
Change the 0 to "$?" to get the exit code instead. To be able to differentiate a number from an error, you may want to use NaN instead, or some error string.
add a comment |
grade=$( echo 0; | tail -n 1 )
This would try to execute ./a.out and then add a line with a single 0 to its output if that program exited with a non-zero exit status or failed to execute at all. The 0 would be caught by tail -n 1 and placed in $grade.
If ./a.out executed correctly and terminated with a zero exit status, the echo would not be triggered.
Remove the redirection of standard error to /dev/null if you are interested in seeing diagnostic messages related to running ./a.out.
Change the 0 to "$?" to get the exit code instead. To be able to differentiate a number from an error, you may want to use NaN instead, or some error string.
add a comment |
grade=$( echo 0; | tail -n 1 )
This would try to execute ./a.out and then add a line with a single 0 to its output if that program exited with a non-zero exit status or failed to execute at all. The 0 would be caught by tail -n 1 and placed in $grade.
If ./a.out executed correctly and terminated with a zero exit status, the echo would not be triggered.
Remove the redirection of standard error to /dev/null if you are interested in seeing diagnostic messages related to running ./a.out.
Change the 0 to "$?" to get the exit code instead. To be able to differentiate a number from an error, you may want to use NaN instead, or some error string.
grade=$( echo 0; | tail -n 1 )
This would try to execute ./a.out and then add a line with a single 0 to its output if that program exited with a non-zero exit status or failed to execute at all. The 0 would be caught by tail -n 1 and placed in $grade.
If ./a.out executed correctly and terminated with a zero exit status, the echo would not be triggered.
Remove the redirection of standard error to /dev/null if you are interested in seeing diagnostic messages related to running ./a.out.
Change the 0 to "$?" to get the exit code instead. To be able to differentiate a number from an error, you may want to use NaN instead, or some error string.
edited yesterday
answered yesterday
Kusalananda♦Kusalananda
139k17259430
139k17259430
add a comment |
add a comment |
Thanks for contributing an answer to Unix & Linux Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509739%2fhow-to-get-either-the-last-line-of-output-or-the-exit-code%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Any objections to running it twice? Once to ensure a zero exit code, subsequently for the output?
– Jeff Schaller♦
2 days ago
@JeffSchaller This is also an option, but it is quite inefficient, especially when there are many simultanous submissions. Consider 100 students submitting simultaneously. There is a noticeable difference between 100 runs and 200 runs.
– Erel Segal-Halevi
2 days ago
1
In
bash, you can usePIPESTATUSinstead of$?:exit 13 | tail -n1; echo $PIPESTATUS[0]– mosvy
2 days ago
@mosvy strangely, this does not work when I capture the output into a variable: *** $ grade=$( ./a.out | tail -1 ) *** bash: ./a.out: No such file or directory *** $ echo $PIPESTATUS[0] *** 0
– Erel Segal-Halevi
2 days ago
1
command substitutions are run in a subshell; you should check the PIPESTATUS inside that subshell:
grade=$(./a.out | tail -1; test $PIPESTATUS[0] = 0 || echo 5)– mosvy
2 days ago