Taking inputs in the script which is space separated and passing this to a function and i have assigned like below
And then when I use for loop for the inputs i got from the user, it is taking only the first argument.
Enter Names : Bala Sundar Sridhar
read names
namesCheck $names
function namesCheck() {
myname=$1
for i in myname
do
printf "\n$i"
done
}
this is printing always the first name .. here as Bala
To keep the forums high quality for all users, please take the time to format your posts correctly.
First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags
```text
and
```
by hand.)
Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.
Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.
The reason is that <space> is a special character to the shell: it is the "field separator". If you feed a command (and a shell function in this regard is similar to a command) some arguments they get plucked from the commandline one by one and the shell supposes them to be separated by blanks:
command arg1 arg2 arg3
"command" will suppose "arg1" to be the first argument, "arg2" to be the second, and so on. If it takes only 2 arguments it will simply ignore the rest . this is what has happened to your other names.
What to do if you want to pass an argument which contains space characters? This is where quoting comes in.
command "arg1 arg2" arg3
Now "command" will suppose "arg1 arg2" to be the first argument and "arg3" to be the second.
No let us examine your script: with the line
namesCheck $names
you feed the function namesCheck 3 arguments, which it gladly receives. The first line in namesCheck() is
myname=$1
which means: take the first argument and store it in $myname. Exactly this is what the shell does - it stores the first argument passed - the first name - into $myname.
To solve this problem you have two possibilities: either pass all the names as one argument, then you could use the for-loop like you did. For this you will have to surround $names by double quotes when you call namesCheck():
nameCheck "$names"
Or you could pass the names as separate arguments, but then the function has to have provisions to deal with multiple arguments, like pravin27 mentioned.