Shell Script - Return Code - File Descriptor - Redirection Operators

 

Return code:

When a command is executed, 3 outcomes will be there. 
Each outcome will be denoted by a number aka return/exit code.
  1. Command executed successfully and gave output. This will be denoted by 0
  2. Command executed successfully and gave NO output.  This will be denoted by 1
  3. Command failed to execute successfully.  This will be denoted by a number greater than 1

Return code will be captured using "$?" and printed using >echo "$?". 

Refer to below screenshot for commands executed and the relevant return codes. In the screenshot, we are executing commands and reading return code into a variable "rc" then printing the value of variable rc using "echo $rc"
  • When we searched for word "root" using grep, command executed and gave output. Hence return code is 0
  • When we searched for word "jamesbond" using grep, command executed and gave NO output. Hence return code is 1
  • When we deliberately gave "grpe" instead of "grep", command failed to execute and gave return code as 127 (which is greater than 1)


File descriptor:

Whenever a shell runs a program, it opens three files with file descriptors 0, 1, and 2. The default assignments for these descriptors are below:
  • 0 - Standard Input  - read - Keyboard
  • 1 - Standard Output - write - Screen
  • 2 - Standard Error  - write - Screen

No comments:

Post a Comment