bash function return status

Vendetta

I have a function

function f() {
  command 1
  command 2
  command 3
  command 4
}

I want function f() to somehow tell me there is an error if any of the 4 commands fails.

I also don't want to set -e. I want four commands all run, even if one fails.

How do I do that? Sorry for the newbie question -- I am quite new to bash scripting.

Random832

If I understand what you're asking correctly, you can do this:

f() {
  err=""
  command 1 || err=${err}1
  command 2 || err=${err}2
  command 3 || err=${err}3
  command 4 || err=${err}4
  # do something with $err to report the error
}

Of course, instead of using a variable you could simply put echo commands after the || if all you need to do is print an error message:

f() {
  command 1 || echo "command 1 failed" >&2
  command 2 || echo "command 2 failed" >&2
  command 3 || echo "command 3 failed" >&2
  command 4 || echo "command 4 failed" >&2
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Trying to understand bash function return values

分類Dev

Bash function does not return value since it seems to run in parallel

分類Dev

Return response with status code in Express

分類Dev

Dynamic return status from restler

分類Dev

Return status of Busybox `timeout` command

分類Dev

Curl to return http status code along with the response

分類Dev

Swift alamofire refactoring trying to return status code

分類Dev

return status code from graphql yoga

分類Dev

What response status code should I return?

分類Dev

How to return different Http Status Code in ServiceStack

分類Dev

How to return 404 status code in ReactJS?

分類Dev

MySQL XDevAPI How to return a successful status

分類Dev

AngularJS $ http.post return status 0

分類Dev

AngularJS $ http get return null status 0

分類Dev

Pipe output and capture exit status in Bash

分類Dev

Identifying mongo server status from bash

分類Dev

Bash pipeline's exit status differs in script

分類Dev

Pass in function as input and return function

分類Dev

Plugin symbol as function return

分類Dev

How to return a grid as a function?

分類Dev

lambda function return objects

分類Dev

Function to Return Node Pointer

分類Dev

Return integer in function String

分類Dev

return array from perl to bash

分類Dev

#!/ bin / bash read if then return to read

分類Dev

bash: expanding function arguments

分類Dev

What is the function of & combined with > bash?

分類Dev

Named bash function parameters

分類Dev

Bash the function is executed twice