Reputation: 15
I have a script with something like this:
git clone ssh://anothersite.com /home/user/another_directory
I need to check if the command has worked, and only then proceed to the next commands. I solved it in a similar way:
if [ "$?" -ne 0 ]; then
echo "{$2} command failed.";
exit 1
I need the word "clone" or another word that will be encountered further in the script instead of {$ 2}. If I substitute $ 0, then it gives me the name of the script that I ran, and not the command "git clone" as I expect
Upvotes: 1
Views: 59
Reputation: 2562
You can use shell functions to achieve that. Here is an example implementation with the function my_git_function
that will display an error message:
# Process git operation
# Parameters : my_git_function [ git_operation [ operation_arguments ] ]
# Return : git exit status code, 0 if NOP or success
my_git_function() {
if [ $# = 0 ]; then
return 0
fi
local git_operation="$1"
shift
if git "$git_operation" "$@"; then
return 0
else
local exit_code="$?"
echo "Command $git_operation failed with exit code $exit_code." >&2
return "$exit_code"
fi
}
# Example with clone
if ! my_git_function clone ssh://anothersite.com /home/user/another_directory
# Failed command, error message already displayed
fi
Upvotes: 3
Reputation: 140970
I need to check if the command has worked
Check with an if
.
if ! git clone ssh://anothersite.com /home/user/another_directory; then
echo "Clone failed" >&2
exit 1
fi
I need the word "clone" or another word that will be encountered further in the script instead of {$ 2}
Write a handy wrapper function and pass command to execute as arguments.
failon() {
if ! "$@"; do
echo "Command failed: $*" >&2
exit 1
fi
}
failon git clone ssh://anothersite.com /home/user/another_directory
Upvotes: 4