-1

On the windows, I write a batch file and the following is the content. How to check it whether error or not on any step? If there is error, then threw message and stop it.

git clone xxx
cd xxx
cd build 
cmake ..
ninja install .
alice
  • 7
  • Does this answer your question? [Batch File try catch](https://stackoverflow.com/questions/21772060/batch-file-try-catch) – Jeremy Thompson Feb 21 '22 at 04:52
  • Can it like the docker ? I dont want to add some try expect or if else. If do this, it will have many try catch to do that – alice Feb 23 '22 at 02:53
  • In computer science there's a saying *Exception Handlers should be used Exceptionally*. What that means is you're going to need a bunch of logic to check all the files exist, the servers online, no special characters to ruin paths or passwords, etc. And that's just the beginning of what can go wrong. If you want to catch each error individually and give the user specific information on which step failed and what the error was then accept the answer below. If your design doesn't warrant Try/Catch's for every line then only use `errorlevel` where obvious things could go wrong. – Jeremy Thompson Feb 23 '22 at 04:14

1 Answers1

2

Use or conditional operators or errorlevel directly:

Also, do not do run multiple cd commands when you can run one.

@echo off
git clone xxx && echo Success || echo Git failed & exit /b 1
cd /d "xxx\build" && echo Success || echo unable to CD & exit /b 1
cmake .. && echo cmake Success || echo cmake failed & exit /b 1
ninja install . && echo Success || echo ninja install error & exit /b 1

to use errorlevel directly, using a single example and also demonstrating pushd and popd instead of cd:

@echo off
git clone xxx
if errorlevel 1 echo Error occurred & exit /b
pushd "xxx\build"
echo run other commands
popd
Gerhard
  • 22,678
  • 7
  • 27
  • 43