In my script I am trying to error check if the first and only argument is equal to -v
, but it is an optional argument. I use an if statement, but I keep getting the unary operator expected error.
This is the code:
if [ $1 != -v ]; then echo "usage: $0 [-v]" exit fi
To be more specific:
This part of the script above is checking an optional argument and then after, if the argument is not entered, it should run the rest of the program.
#!/bin/bash if [ "$#" -gt "1" ]; then echo "usage: $0 [-v]" exit fi if [ "$1" != -v ]; then echo "usage: $0 [-v]" exit fi if [ "$1" = -v ]; then echo "`ps -ef | grep -v '\['`" else echo "`ps -ef | grep '\[' | grep root`" fi
To prevent this script from throwing the “unary operator expected” error on bash, we need to update the code once again. We have to add the double quotes around the left expression “$v,” as we have done in the image below. The rest of the code will be unchanged for now. Now, the code is ready for use.
The word unary is basically synonymous with “single.” In the context of mathematics, this could be a single number or other component of an equation. So, when Bash says that it is expecting a unary operator, it is just saying that you are missing a number in the script.
A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.
$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) . Follow this answer to receive notifications. edited Jun 20, 2020 at 9:12. CommunityBot.
Quotes!
if [ "$1" != -v ]; then
Otherwise, when $1
is completely empty, your test becomes:
[ != -v ]
instead of
[ "" != -v ]
...and !=
is not a unary operator (that is, one capable of taking only a single argument).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With