0

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?

2
  • Yes. Would help if solution is POSIX compliant Commented Apr 30, 2022 at 1:26
  • I'm not sure I actually recommend this but: 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 with index($0,find) or matching it as a regular expression with $0~find. Commented Apr 30, 2022 at 3:07

1 Answer 1

0

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
1
  • Thanks, I think this can work for now, but I hope there is a quicker way as you said. Commented Apr 30, 2022 at 1:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .