Results 1 to 8 of 8
I would like to include a validation within a script that displays usage information when an error message is returned by the command:
if <error is returned> then //standard error
...
- 10-08-2008 #1Just Joined!
- Join Date
- Nov 2007
- Posts
- 8
Scripting help
I would like to include a validation within a script that displays usage information when an error message is returned by the command:
if <error is returned> then //standard error
echo usage command parameter1 | parameter2
fi
- 10-09-2008 #2Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
slyth,
Usually most errors result in an exit and return a non-zero value, therefore you cannot wait for error to happen. It's better to detect conditions in which error will happen. Say you are writing a script that expects 1 argument, you can do a test if the condition is met before doing anything else:
#/bin/bash
[ $# -eq 1 ] || { echo "usage: `basename $0` para1"; exit 1; }
This script is equivalent to
#/bin/bash
if [ $# -ne 1 ]; then
echo "usage: `basename $0` para1"fi
exit 1
which is much easier to understand.
- 10-09-2008 #3
If you mean how you can run a program and then report an error if the program errors, consider something like this:
Virtually every program (I say "virtually", but really, every program) will exit with code 0 if they are successful, and non-zero if there was an error. The above code executes a command, and then if the return code is non-zero, executes the code in the if statement.Code:if ! some_command; then # Error fiDISTRO=Arch
Registered Linux User #388732
- 10-09-2008 #4Just Joined!
- Join Date
- Nov 2007
- Posts
- 8
The following script doesn't compile somehow, see anything wrong?
What does $# represent?
#/bin/bash
if [$# -eq 1]; then
echo "usage: test arg";
exit 1;
fi
if [$1 -eq "arg"] then
exit 0
fi
./test
[root@localhost bin]# ./test
./test: line 2: [0: command not found
./test: line 9: syntax error near unexpected token `fi'
./test: line 9: `fi'
[root@localhost bin]#
- 10-09-2008 #5Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
should be
#/bin/bash
if [ $# -ne 1 ]; then
echo "usage: test arg"
exit 1;
fi
if [ "$1" == "arg" ]; then
exit 0
fi
Please note the spaces around the conditional expressions.
- 10-09-2008 #6Just Joined!
- Join Date
- Nov 2007
- Posts
- 8
No luck yet
- 10-09-2008 #7Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Try to use single '=' instead of double in the string comparison:
if [ "$1" = "arg" ]; then
- 10-12-2008 #8Just Joined!
- Join Date
- Oct 2008
- Posts
- 44


Reply With Quote
