How can I get the position of an argument by using its value?
For example:
myScript.sh hello world
echo "$1"
hello
How can I get the position of 'hello', which is 1 in this case?
While it wouldn't surprise me if there were quicker, easier ways, something like this should work:
#!/bin/bash
pos=0
found=no
for arg ; do
let pos++
if [[ "$arg" == "hello" ]] ; then
found=yes
break
fi
done
if [[ "$found" == "yes" ]] ; then
echo "Found hello at position $pos"
else
echo "hello not found"
fi
printf '%s\0' "$@" | awk -vRS='\0' -vfind=hello '$0==find{print NR;exit}'
(all POSIX). Omit exit if there may be multiple matches and you want all of them. You can also find the argument(s) containing a string withindex($0,find)
or matching it as a regular expression with$0~find
.