- /* steve jansen */
- // another day in paradise hacking code and more
- Windows Batch Scripting: Return Codes
- Return Code Conventions
- Checking Return Codes In Your Script Commands
- Conditional Execution Using the Return Code
- Tips and Tricks for Return Codes
- Some Final Polish
- Comments
- Guides
- Recent Posts
- Social Stuff
- Main() return values (C# Programming Guide)
- Example
- Sample output
- Async Main return values
- Compiler-generated code
- Return code script windows
- Answered by:
- Question
- Answers
- All replies
- Returning value from called function in a shell script
- 5 Answers 5
- 1. Echo strings
- 2. Return exit status
- 3. Share variable
- Not the answer you’re looking for? Browse other questions tagged shell return-value or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Return Codes
Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even skilled Windows programmers overlook the importance of return codes.
Return Code Conventions
By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages typically don’t effect the return code. What matters is did the script work or not?
Checking Return Codes In Your Script Commands
The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. A very helpful feature is the built-in DOS commands like ECHO , IF , and SET will preserve the existing value of %ERRORLEVEL% .
The conventional technique to check for a non-zero return code using the NEQ (Not-Equal-To) operator of the IF command:
Another common technique is:
The ERRORLEVEL 1 statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity check for non-zero with the NEQ 0 style than assuming return codes will be 1 or greater on error.
You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply calling the program and checking for return code 9009.
It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.
Conditional Execution Using the Return Code
There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must conform to the convention of returning 0 on success and non-0 on failure for this to work.
To execute a follow-on command after sucess, we use the && operator:
To execute a follow-on command after failure, we use the || operator:
I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing when an error is raised. You have to code for halting on error.
A very simple way to halt on error is to use the EXIT command with the /B switch (to exit the current batch script context, and not the command prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.
A simliar technique uses the implicit GOTO label called :EOF (End-Of-File). Jumping to EOF in this way will exit your current script with the return code of 1.
Tips and Tricks for Return Codes
I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea because other callers may use the IF ERRORLEVEL 1 syntax to check your script.
I also recommend documenting your possible return codes with easy to read SET statements at the top of your script file, like this:
Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.
Some Final Polish
One small piece of polish I like is using return codes that are a power of 2.
This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code. This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t have access to the target systems.
If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were raised.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
Main() return values (C# Programming Guide)
You can return an int from the Main method by defining the method in one of the following ways:
Main method code | Main signature |
---|---|
No use of args or await | static int Main() |
Uses args , no use of await | static int Main(string[] args) |
No use of args , uses await | static async Task Main() |
Uses args and await | static async Task Main(string[] args) |
If the return value from Main is not used, returning void or Task allows for slightly simpler code.
Main method code | Main signature |
---|---|
No use of args or await | static void Main() |
Uses args , no use of await | static void Main(string[] args) |
No use of args , uses await | static async Task Main() |
Uses args and await | static async Task Main(string[] args) |
However, returning int or Task enables the program to communicate status information to other programs or scripts that invoke the executable file.
The following example shows how the exit code for the process can be accessed.
Example
This example uses .NET Core command-line tools. If you are unfamiliar with .NET Core command-line tools, you can learn about them in this get-started article.
Modify the Main method in program.cs as follows:
When a program is executed in Windows, any value returned from the Main function is stored in an environment variable. This environment variable can be retrieved using ERRORLEVEL from a batch file, or $LastExitCode from PowerShell.
You can build the application using the dotnet CLI dotnet build command.
Next, create a PowerShell script to run the application and display the result. Paste the following code into a text file and save it as test.ps1 in the folder that contains the project. Run the PowerShell script by typing test.ps1 at the PowerShell prompt.
Because the code returns zero, the batch file will report success. However, if you change MainReturnValTest.cs to return a non-zero value and then recompile the program, subsequent execution of the PowerShell script will report failure.
Sample output
Async Main return values
Async Main return values move the boilerplate code necessary for calling asynchronous methods in Main to code generated by the compiler. Previously, you would need to write this construct to call asynchronous code and ensure your program ran until the asynchronous operation completed:
Now, this can be replaced by:
The advantage of the new syntax is that the compiler always generates the correct code.
Compiler-generated code
When the application entry point returns a Task or Task , the compiler generates a new entry point that calls the entry point method declared in the application code. Assuming that this entry point is called $GeneratedMain , the compiler generates the following code for these entry points:
- static Task Main() results in the compiler emitting the equivalent of private static void $GeneratedMain() => Main().GetAwaiter().GetResult();
- static Task Main(string[]) results in the compiler emitting the equivalent of private static void $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
- static Task Main() results in the compiler emitting the equivalent of private static int $GeneratedMain() => Main().GetAwaiter().GetResult();
- static Task Main(string[]) results in the compiler emitting the equivalent of private static int $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
If the examples used async modifier on the Main method, the compiler would generate the same code.
Return code script windows
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Server 2008 R2 scheduled task not working — action «C:\Windows\SYSTEM32\cmd.exe» with return code 1
Answers
Server 2008 R2 scheduled task not working — action «C:\Windows\SYSTEM32\cmd.exe» with return code 1
- Create a separate simple script for the program which you want to run/test and save it in C:\tasks\ and give the script path in Actions tab.
- Choose the security option «Run whether user logged on or not» as per below snapshot and check for the difference.Also check history to know more about the task how is running, is there errors/warning.
Thank you and write here again if problem persists.
Regards, Ravikumar P
All replies
Please check the link http://www.blogfodder.co.uk/2012/4/20/win-2008-task-scheduler-with-return-code-1-0x1.
If it helps you.
Thanks, Swapnil Prajapati
Its not helping me at all.
I have checked this before and not fruitful to me ..
any other suggestion please.
Server 2008 R2 scheduled task not working — action «C:\Windows\SYSTEM32\cmd.exe» with return code 1
- Create a separate simple script for the program which you want to run/test and save it in C:\tasks\ and give the script path in Actions tab.
- Choose the security option «Run whether user logged on or not» as per below snapshot and check for the difference.Also check history to know more about the task how is running, is there errors/warning.
Thank you and write here again if problem persists.
Regards, Ravikumar P
That does not help at all.
I think Microsoft dropped ball on windows 2008, and just wondering intentionaly or not.
So far windows 2003 is the best server platform created in terms of maintenance. And if someone from Microsoft actually reading postings here can you please roll back security changes implemented in windows 2008 because those changes makes system unstable and basically useless for businesses, meanwhile hackers have a field days with it.
I working with task schedulers since 1996 and so far this is the worse of all. So many permissions issues that we switch our batch server back to 2003 and hopping that windows 2012 will not have that many loose screws.
Returning value from called function in a shell script
I want to return the value from a function called in a shell script. Perhaps I am missing the syntax. I tried using the global variables. But that is also not working. The code is:
5 Answers 5
A Bash function can’t return a string directly like you want it to. You can do three things:
- Echo a string
- Return an exit status, which is a number, not a string
- Share a variable
This is also true for some other shells.
Here’s how to do each of those options:
1. Echo strings
2. Return exit status
3. Share variable
You are working way too hard. Your entire script should be:
but even that is probably too verbose. I would code it:
but the resulting error message is a bit obscure.
If it’s just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:
I think returning 0 for succ/1 for fail (glenn jackman) and olibre’s clear and explanatory answer says it all; just to mention a kind of «combo» approach for cases where results are not binary and you’d prefer to set a variable rather than «echoing out» a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
as in (yep, the example is somewhat silly, it’s just an.. example)
In case you have some parameters to pass to a function and want a value in return. Here I am passing «12345» as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE
Not the answer you’re looking for? Browse other questions tagged shell return-value or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.