HI ,I am a new in Bash and ,I dont know how to pass a second parameter to this fuction,if the name of the passed argument is num works fine,but if I try to pass secondNum,dont recognized it
thanks
function check()
{
if(($(echo ${#num}) == 0 ))
then
echo No arguments passed.Try again
else
rem=$(echo $num | tr -d [0-9])
lenght=$(echo ${#rem})
if(( $lenght > 0))
then
echo "$num is not a number"
else
echo "$num is a number"
fi
fi
}
Thanks for the respond.I try to do it this way,why is not working
Thanks
#!/bin/bash
function check()
{
if(($(echo ${#num}) == 0 ))
then
echo No arguments passed.Try again
else
rem=$(echo $num | tr -d [0-9])
lenght=$(echo ${#rem})
if(( $lenght > 0))
then
echo "$num is not a number"
else
echo "$num is a number"
fi
fi
}
echo -n "Enter: "
read fnum
let num=fnum
check "$num"
echo -n "Enter: "
read snum
let num=snum
check "$num"
#!/usr/bin/ksh or bash or dash or ...
####
check()
{
# function args are just like command line args - you call function as command
# return in function works same way as exit in script
[ $# -lt 1 ] && echo "No arguments passed.Try again" >&2 && return 1
for num in $@
do
other=${num//[0-9]/} # remove numbers = like tr -d "[0-9]"
[ "$other" != "" ] && echo "$num is not a number" >&2 && return 2
echo "$num is number"
done
}
#####MAIN####
echo -n "Enter: "
read num1
check $num1
stat=$?
echo $stat
echo "________________"
echo -n "Enter: "
read num2
check $num2
stat=$?
echo $stat
echo "_________________"
check $num1 $num2
Thank you very much ,but I didnt understand the sintacsis ,could you show me what to replace in my file,because mine is working fine with one variable passed
Thanks
Use args, not global variable, if you are writing function with args. I and jsmithstl have given examples how to use arguments in function case. Same way as for script.
in bash $1 $2 $3 ...... $N where N is any number (once you hit 10+ enclose them ex: ${10}) refers to the arguments passed to the function. So...
myFunction arg1 arg2 arg3
can be read with
echo "$1" "$2" "$3"
Respectively...$# gives you the amount of arguments (useful if you want to make sure the correct amount of args are given before continuing.) I hope I helped. I'm not that good at explaining things...