Reputation: 454
In this shellscript, I have created 3 functions. It will take 2 command line arguments. first for the type of the operation and second for a string to perform something on it.. Here, my echo command in any of the functions is not printing anything..
Any Help would be appreciated.
clear
lower()
{
echo $2 | tr "[A-Z]" "[a-z]"
}
upper()
{
echo $2 | tr "[a-z]" "[A-Z]"
}
proper()
{
echo $2 | sed 's/.*/\L&/; s/[a-z]*/\u&/g'
}
#echo "Enter The Option and then the string to perform the operation:"
echo $1 $2 '> echo $1 $2 '
if [ $1 = "-l" ]
then
lower $2
elif [ $1 = "-u" ]
then
upper $2
elif [ $1 = "-p" ]
then
proper $2
fi
Upvotes: 3
Views: 5498
Reputation: 361605
Outside of a function, $1
, $2
, etc., refer to the command-line arguments to the program. Inside of a function, they are the function's arguments. Change all of the echo $2
's to echo $1
.
Style improvements:
By default, always quote variable expansions. Write "$1"
and "$2"
instead of bare $1
and $2
. That way if those arguments have spaces or globs they'll expand to one word instead of many.
The if
/elif
chain at the bottom could be replaced with a case
block.
case "$1" in
-l) lower "$2";;
-u) upper "$2";;
-p) proper "$2";;
esac
Putting clear
at the top of a script is kind of an annoying DOS-ism. On Linux, I don't want scripts I run clearing my terminal as if they know best. Either get rid of the clear
; or, if you want to be fancy, add tput smcup
at the top and tput rmcup
at the bottom to save and restore the terminal. That's what programs like less
and vim
do to draw to the whole screen and then restore the original terminal contents when they exit.
Upvotes: 2
Reputation: 11479
Inside each function, replace $2
with $1
.
lower()
{
echo $1 | tr "[A-Z]" "[a-z]"
}
For your script and also for your function, $1
represents the first argument and $2
second. If you are going to provide two arguments to your script, but one argument to your function, then it should be,
$ cat test.sh
#!/bin/bash
echo "$1" "$2"
func_echo(){
echo "func $1"
}
# Call the function
func_echo $2
Resulted in:
$ ./test.sh "first" "second"
first second
func second
Upvotes: 1