Search code examples
bashhttp-redirectstderr

bash: Unable to get one-liner with stderr redirect and || operator to work


I've got the following code which always exits, regardless of success of first command

git pull $newURL $branch 2>/dev/null || echo "Unable to connect to git repository @ $gitURL" && exit 1

What am I doing wrong? I can, of course, split it into an if using:

if [ $? == 0 ]

but I like the neater version.


Solution

  • Assuming you only want to exit in the "else" error condition, group those two commands together:

    git pull "$newURL" "$branch" 2>/dev/null || { echo "Unable to connect to git repository @ $gitURL" && exit 1; }
                                        here ---/ ..............................................................\--- and here
    

    The semicolon is required, to end the list of commands inside the braces.