compare as numeric value. unix - linux

So I am trying to test a few things coding in bash. As a n00b I am having some problems with the basics and how irritating it can get using shell dealing with numbers.
if $((echo $?)) > 0 ;then
echo "there is an error";
else
echo "it passed";
fi
the error I get is :
bash: echo 0: syntax error in expression (error token is "0")
I tried without the echo and I get:
bash: ./0: Permission denied
so I am a bit confused what the shell is trying to do.
Thanks

The whole arithmetic evaluation must be within double parentheses:
if (($? > 0)) ;then
echo "there is an error";
else
echo "it passed";
fi

try this:
OUT=$?
if [ $OUT -eq 0 ];then
echo "OK!"
else
echo "NOT OK!"
fi

Related

Problems with the control design [duplicate]

This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Closed 3 months ago.
Good evening (or day. Whichever)! I ran into a problem while writing a bash script. I have the code
#!/bin/bash
echo "Available options:"
echo "1. text"
echo "2. exit"
read var1
echo
if [[$var -ge 0]]; then
echo "hello world"
elif [[$var -ge 1]]; then
echo "good bye"
else
echo "error"
fi
and all the time it puts the emphasis on the operator
./proba3.sh: line 9: [[: command not found
./proba3.sh: line 11: [[: command not found
I tried many variations of the branching operation, but still get the same error. I will be very glad for advice or hints on how to fix this error. Thanks in advance
You need spaces inside the brackets.
Also you misspelled the variable name.
Finally, you should probably test for equality not ge
Fixed:
#!/bin/bash
echo "Available options:"
echo "1. text"
echo "2. exit"
read var
echo
if [[ $var -eq 1 ]]; then
echo "hello world"
elif [[ $var -eq 2 ]]; then
echo "good bye"
else
echo "error"
fi

Bash IF/ELIF statements

So I am learning bash and wanted to make a script to 'automate' a collection of kali tools. Basically I do not understand why the if statement code is being triggered regardless if condition is true or false.
#!/bin/bash
#requires root or sudo priv
#check for a successful ping
target_ip=$1
nmap_opt = " "
#nmap options variables --
nmap_os="-O"
nmap_version="-sV"
nmap_udp="-sU"
nmap_stealth="-sS"
nmap_aggr="-A"
nmap_option_input_temp=""
ping $target_ip -c 5
if [ $? -eq 0 ]; then
echo "successful ping on" $target_ip
else
echo "ping unsuccessful, check VPN connection or host may be down"
exit 1
fi
read -p "enter pathway for nmap output: " nmap_file
read -p "detect os? (y/n) " nmap_option_input_temp
#add loops for y/n user input
if [[ ${nmap_option_input_temp} -eq "y" ]];
then
nmap_opt="${nmap_opt} ${nmap_os}"
elif [[ ${nmap_option_input_temp} -eq "n" ]];
then
nmap_opt=$nmap_opt
else
echo "invalid option"
fi
read -p "detect version? (y/n) " nmap_option_input_temp
#add loops for y/n user input
if [[ ${nmap_option_input_temp} -eq "y" ]];
then
nmap_opt="${nmap_opt} ${nmap_version}"
elif [[ ${nmap_option_input_temp} -eq "n" ]];
then
nmap_opt=$nmap_opt
else
echo "invalid option"
fi
echo "nmap selected option/s:" $nmap_opt
echo $nmap_option_input_temp
#starting nmap..
sudo nmap $nmap_opt -oN $nmap_file $target_ip
this is the nmap_opt variable echo out even when both inputs are 'n'
nmap selected option/s: -O -sV
Let me know if there is anything I missed in the explanation!
-eq is for integer comparisons. Use ==:
if [[ "${nmap_option_input_temp}" == y ]];
And fix your quotes. Fixed strings like y don't need to be quoted. Inside [[, variables don't need to be quoted, but IMO you should quote them anyway for consistency.
This error would be more easily spotted if you used the more conventional:
if [ "${nmap_option_input_temp}" -eq y ]; # Still incorrect!!
since you would get a nice error message.
Note that the fix with [ is slightly different, and you should use a single =:
if [ "${nmap_option_input_temp}" = y ];
The == operator is a bashism which does not really add any value. But really, you should not be using if/elif at all here. This is the perfect place for a case statement:
case "${nmap_option_input_temp}" in
y) nmap_opt="${nmap_opt} ${nmap_os}";;
n) ;;
*) echo "invalid option" >&2 ;;
esac

writing a guessing game in linux and I keep receiving error message: syntax error near unexpected token 'done

Im writing a number guessing game its a bash script in linux. Every time I go to run my code I receive this error message: line 17: syntax error near unexpected token `done'
\#!/bin/bash
random_number= $(( ( RANDOM % 100 ) +1 ))
echo $rand
user_guess=0
guesses=0
while \[ $user_guess -ne $random_number \] do
read -p "Enter guess : " ; user_guess
if \["$user_guess" -lt $random_number \] ; then
echo "Select a Higher Number"
elif \[ "$ user_guess" -gt $random_number \]; then
echo "Select a Lower Number"
fi
guesses=$(($guesses + 1))
echo "Correct! Guessed $random_number It took $guesses guessess."
done
I tried running my code but was unable to due to error message
there was several syntax errors with your code.
missing ; after while statement
no space between [ and $user_guess in the first if statement and a couple more...
also a logic error, the echo correct is in your while loop, so it is always correct even when you don't have the good answer.
adding indentation to your code will help you making it readable.
quotes your variables everywhere you can
other than that, you were on the right track.
#!/bin/bash
RANDOM_NUMBER=$((( RANDOM % 100 ) +1 ))
USER_GUESS=0
GUESSES=0
while [[ "$USER_GUESS" -ne "$RANDOM_NUMBER" ]]; do
read -p "Enter guess : " USER_GUESS
if [[ "$USER_GUESS" -lt "$RANDOM_NUMBER" ]]; then
echo "Select a Higher Number"
elif [[ "$USER_GUESS" -gt "$RANDOM_NUMBER" ]]; then
echo "Select a Lower Number"
fi
GUESSES=$(($GUESSES + 1))
done
echo "Correct! Guessed ${RANDOM_NUMBER} It took ${GUESSES} guesses."

Why doesn't string comparison with wildcards work properly?

I wrote this shell code, but it doesn't get the good output.
Even though the $csoport gets the "...: No such user" output, id doesn't echoes the following line I wrote there.
read felhasznalo
while [ "$felhasznalo" != "exit" ]
do
csoport=`groups $felhasznalo`
echo "$csoport"
if [[ "$csoport" == *": No such user"* ]] ; then
echo -n "Nincs ilyen felhasznalo a rendszerben"
else
echo "$csoport"
fi
echo -n "Felhasznalo: "
read felhasznalo
done
You shouldn't try to match the error messsage since you only care if groups fails. You ought to do:
if ! csoport=$(groups "$felhasznalo"); then
printf "Nincs ilyen felhasznalo a rendszerben"
else
echo "$csoport"
fi

How do I set a default action for when the URL passed to lynx is invalid?

My goal is to write a little bash script that outputs the contents of the given PHP function's manual page to the terminal. My current script (pfunc) is as follows:
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi
It's working as expected so far:
me#mybox:~$ pfunc rand | head -17
produces
rand — Generate a random integer
Description
int rand ( void )
int rand ( int $min , int $max )
If called without the optional min, max arguments rand() returns a
pseudo-random integer between 0 and [74]getrandmax(). If you want a
random number between 5 and 15 (inclusive), for example, use rand(5,
15).
Note: On some platforms (such as Windows), [75]getrandmax() is only
32767. If you require a range larger than 32767, specifying min and
max will allow you to create a range larger than this, or consider
using [76]mt_rand() instead.
Whenever an invalid URL is passed, I would like to print a messages like "That function doesn't exist in PHP" or something, instead of silently returning to the command prompt. Could anyone provide a little insight on how to do this? Thanks in advance.
PHP.net returns a successful response regardless of whether or not the query was successful, so you can't check the HTTP status code like you would in well behaved web sites.
You can instead use a kludge like this:
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
if [[ $contents == *"doesn't exist. Closest matches"* ]]
then
echo "No such function" >&2
else
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi
fi
You could parse the response of lynx (or others ways like wget, curl, lwp-request) to determine if the function doesn't exist.
An example with lwp-request :
[neumann#MacBookPro ~]$ GET "http://php.net/$func"|grep "<b>$func</b> doesn'\t exist"
<b>toto</b> doesn't exist. Closest matches:
[neumann#MacBookPro ~]$ func=preg_match
[neumann#MacBookPro ~]$ GET "http://php.net/$func"|grep "<b>$func</b> doesn'\t exist"
[neumann#MacBookPro ~]$
So you could try something like :
existFunction(){
lwp-request -mget "http://php.net/$1"|grep "<b>$1</b> doesn'\t exist" >/dev/null || echo "1"
}
if [[ $(existFunction $1) = 1 ]]; then
echo "YES"
fi
NB : GET is an alias of "lwp-request -mget".
What I would do based on your script :
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
if [[ $contents =~ $func[[:space:]]+doesn.t[[:space:]]+exist.[[:space:]]+Closest[[:space:]]+matches ]]
then
echo >&2 "php.net don't have a page for $func"
exit 1
fi
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi

Resources