Ksh Script Error Checking
Contents |
and Signals and Traps (Oh My!) - Part 1 by William Shotts, Jr. In this lesson, we're going to look at handling errors during the execution of your scripts. The difference shell script error handling between a good program and a poor one is often measured in
Shell Script Exit Code
terms of the program's robustness. That is, the program's ability to handle situations in which something goes wrong. Exit
Bash Script Trap
status As you recall from previous lessons, every well-written program returns an exit status when it finishes. If a program finishes successfully, the exit status will be zero. If the exit status
Ksh Error Handling
is anything other than zero, then the program failed in some way. It is very important to check the exit status of programs you call in your scripts. It is also important that your scripts return a meaningful exit status when they finish. I once had a Unix system administrator who wrote a script for a production system containing the following 2 lines shell script exit on error of code: # Example of a really bad idea cd $some_directory rm * Why is this such a bad way of doing it? It's not, if nothing goes wrong. The two lines change the working directory to the name contained in $some_directory and delete the files in that directory. That's the intended behavior. But what happens if the directory named in $some_directory doesn't exist? In that case, the cd command will fail and the script executes the rm command on the current working directory. Not the intended behavior! By the way, my hapless system administrator's script suffered this very failure and it destroyed a large portion of an important production system. Don't let this happen to you! The problem with the script was that it did not check the exit status of the cd command before proceeding with the rm command. Checking the exit status There are several ways you can get and respond to the exit status of a program. First, you can examine the contents of the $? environment variable. $? will contain the exit status of the last command executed. You can see
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow try catch in shell script the company Business Learn more about hiring developers or posting ads with us Stack bash script ignore error continue Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community bash trap error of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Error handling in unix shell ksh up vote 1 down vote favorite 1 Can anyone guide to http://linuxcommand.org/wss0150.php a document or explain on the below how to use error handling in ksh. How does Unix work on unhandled errors(like error happened in the subscript etc..). unix ksh share|improve this question asked Dec 23 '15 at 7:50 xGen 158110 add a comment| 1 Answer 1 active oldest votes up vote 3 down vote accepted From ksh man page. Unhandled errors Errors detected by the shell, such as syntax errors, cause the http://stackoverflow.com/questions/34431000/error-handling-in-unix-shell-ksh shell to return a non-zero exit status. If the shell is being used non-interactively, then execution of the shell file is abandoned UNLESS the error occurs inside a subshell in which case the subshell is abandoned. Error handling Basically check exit/return codes to handle errors: if [ $exit_code != 0 ]; then # Your error handler fi Example test_handler() { ls file_not_present if [ $? -eq 2 ]; then echo "Handler for No such file or directory" elif [ $? -ne 0]; then echo "Handler for any other exception" else echo "Succesful execution" fi } Will throw: ls: cannot access non_file: No such file or directory Handler for No such file or directory But if the command does not exit: test_handler() { l file_not_present if [ $? -eq 2 ]; then echo "Handler for No such file or directory" elif [ $? -ne 0 ]; then echo "Handler for any other exception" else echo "Succesful execution" fi } The output will be: l: not found [No such file or directory] Handler for any other exception The shell returns the exit status of the last command executed (see also the exit command above). Run time errors detected by the shell are reported by printing the command or function name and the error condition. If
about a specific product or take a course and get certified. So, what do you want to learn about? Choose a topic Featured topics Mobile https://www.ibm.com/developerworks/aix/library/au-kornshellscripting/ development Big data Cognitive computing Cloud Featured destinations Swift @ IBM developerWorks Open Architecture center developerWorks Premium Develop Develop with our trials & downloads Start developing with product trials, free downloads, http://docstore.mik.ua/orelly/unix3/korn/ch08_04.htm and IBM Bluemix™ services. Sort by topic or product name and find everything we have to offer. View all downloads & trials Featured products Bluemix Websphere Application Server DB2 Express shell script C MobileFirst Platform Foundation Featured destinations Swift @ IBM developerWorks Open Architecture center API Explorer Connect Find a community and connect Learn from the experts and share with other developers in one of our dev centers. Ask questions and get answers with dW answers. Search for local events in your area. All in developerWorks communities. View communities Featured Developer Centers Jazz.net shell script exit IBM Cloud Analytics DEV Bluemix API Explorer Featured destinations Swift @ IBM developerWorks Open Architecture center developerWorks Premium Career Concierge dW Open Architecture Center Swift @ IBM LearnAIX and UNIX ContentsIntroductionWhat is a shell?Writing your first Korn shell scriptVariablesKorn shell nuts and boltsError checkingThe dollar question mark ($?)Standard in, out, and errorFunctionsThe case statementPutting a whole script togetherFeeding input into a script from the command lineE-mail from a scriptConclusionDownloadable resourcesRelated topicsComments Korn shell scriptingA beginner’s guide Kurt RileyPublished on June 17, 2008 What is a shell?The IBM® AIX® operating system and other UNIX-like operating systems need a way to communicate with the kernel. This is done is through the use of a shell. There are a few different shells that you can use, but this article focuses on the Korn shell. The Korn shell is the default shell used with AIX. When you log into AIX, you are started at a prompt in a certain directory. The default directory is usually your home directory. The reason it's called a home directory is because the directory structure is usually something like this:
earlier that programs in general can be set up to "trap" specific signals and process them in their own way. The trap built-in command lets you do this from within a shell script. trap is most important for "bullet-proofing" large shell programs so that they react appropriately to abnormal events -- just as programs in any language should guard against invalid input. It's also important for certain systems programming tasks, as we'll see in the next chapter. The syntax of trap is: trap cmd sig1 sig2 ... That is, when any of sig1, sig2, etc., are received, run cmd, then resume execution. After cmd finishes, the script resumes execution just after the command that was interrupted.[121] [121] This is what usually happens. Sometimes the command currently running aborts (sleep acts like this, as we'll see soon); other times it finishes running. Further details are beyond the scope of this book. Of course, cmd can be a script or function. The sigs can be specified by name or by number. You can also invoke trap without arguments, in which case the shell prints a list of any traps that have been set, using symbolic names for the signals. If you use trap -p, the shell prints the trap settings in a way that can be saved and reread later by a different invocation of the shell. The shell scans the text of cmd twice. The first time is while it is preparing to run the trap command; all the substitutions as outlined in Chapter 7 are performed before executing the trap command. The second time is when the shell actually executes the trap. For this reason, it is best to use single quotes around the cmd in the text of the shell program. When the shell executes the trap's command, $? is always the exit status of the last command run before the trap started. This is important for diagnostics. Here's a simple example that shows how trap works. Suppose we have a shell script called lo