I am having issues handling arguments that contain white spaces in a my bash script.
The script
#!/bin/bash
for i in $*
do
echo
Change $*
to "$@"
on the first line.
What you want is $@ for the parameters (and you have to enclose it in "") instead of $*.
Replying to the comment left in 2011 on how to assign each argument to a variable...
This bash function assigns each argument to an item in an array. These can then be used elsewhere.
The function in question finds files of a certain type and then greps them:
search "multi word search terms" txt
The relevant lines are the the first 5. We initialise an array, loop over the arguments passed, and assign them as items in the array. These are then referenced by the function as required.
This way you can specify an optional 3rd parameter to open the files in an editor of your choice:
search "multi word search terms" txt mate
The variable $searchterm has had spaces escaped so that grep will accept it as one string.
function search() {
terms=();
for i in "$@"
do
terms+=("$i")
done
file='*.'${terms[1]};
searchterm=${terms[0]// /\\ };
if [ -n "$3" ]; then
find . -type f -name $file -exec grep -irl "$searchterm" {} \; | xargs ${terms[2]};
else
find . -type f -name $file -exec grep -irl "$searchterm" {} \;;
fi
}
Hope this helps someone!