Question
Write a Bash script that would execute the following commands and print their exit statuses:
1. date
2. date blah
3. somenonexistingcommand
1. date
2. date blah
3. somenonexistingcommand
Answers
Bot
Here is the Bash script that would execute the following commands and print their exit status:
```
#!/bin/bash
# Execute command 1 and print the exit status
date
echo "Command 1 Exit Status: $?"
# Execute command 2 and print the exit status
date blah
echo "Command 2 Exit Status: $?"
# Execute command 3 and print the exit status
somenonexistingcommand
echo "Command 3 Exit Status: $?"
```
Explanation:
- `#!/bin/bash` is the shebang that specifies the script should be executed in Bash shell.
- The first command `date` will get the current date and time and show it on the console.
- `$?` is a special variable in Bash that returns the exit status of the last executed command. By printing it, we can see whether the command was successful (0) or had an error (non-zero).
- The second command `date blah` will produce an error because `blah` is not a valid option for `date`.
- The third command `somenonexistingcommand` will also produce an error because it is not a valid command.
When you run this script, it will output the current date and time followed by the exit statuses of each command.
```
#!/bin/bash
# Execute command 1 and print the exit status
date
echo "Command 1 Exit Status: $?"
# Execute command 2 and print the exit status
date blah
echo "Command 2 Exit Status: $?"
# Execute command 3 and print the exit status
somenonexistingcommand
echo "Command 3 Exit Status: $?"
```
Explanation:
- `#!/bin/bash` is the shebang that specifies the script should be executed in Bash shell.
- The first command `date` will get the current date and time and show it on the console.
- `$?` is a special variable in Bash that returns the exit status of the last executed command. By printing it, we can see whether the command was successful (0) or had an error (non-zero).
- The second command `date blah` will produce an error because `blah` is not a valid option for `date`.
- The third command `somenonexistingcommand` will also produce an error because it is not a valid command.
When you run this script, it will output the current date and time followed by the exit statuses of each command.