I have this script:

USERS=("user1.com" "user2.co.uk" "user3.com")
PASSES=("pass1" "pass2" "pass3")

for i in ${USERS[@]}; do
    echo ${PASSES[i]};

running this script outputs:

my-script.sh: line 6: user1.com: syntax error: invalid arithmetic operator (error token is ".com")

However, my values are wrapped in quotes and as far as I know, echo isn't an arithmetic operation.

Coming from a PHP background, this is confusing. In PHP we can do:

echo gettype($string);
echo gettype($int);

which outputs


Yet, the quotes seemingly do not do as I'd think. How do I force string usage instead of treating user1.com as user1 . com?

  • just a general question to the community: should this more be on SO or is ok here? – treyBake Jun 5 '19 at 12:07
  • The problem is that you are trying to de-reference an indexed array with a string; your loop should be over the indices of USERS i.e. for i in ${!USERS[@]} ... – steeldriver Jun 5 '19 at 12:14
  • @steeldriver huh that did it! Can you tell me what adding the ! before the array does in the foreach loop? (or add an answer for some free rep ;)) – treyBake Jun 5 '19 at 12:16
  • to downvoter: not fussed on the vote, but leave a comment so I can get better :) – treyBake Jun 5 '19 at 13:03
  • It's an indirection operator, it produces the indices into the array rather than the list of values. (All Bash variables are essentially strings anyway, but some strings contain numbers,) – tripleee Jun 5 '19 at 13:21

Your current code expands to

for i in user1.com user2.co.uk user3.com; do
    echo ${PASSES[i]};

which of course makes no sense at all. The indirection operator produces a list of array indices instead:

bash$ echo "${!USERS[@]}"
0 1 2

So with that, you can loop over the individual indices. Let's also add correct quoting.

for i in ${!USERS[@]}; do
    echo "${PASSES[i]}"

For full points, you should not use upper case for your private variables; uppercase variable names are reserved for system use.

  • didn't know that bout var names, I just see like every tutorial use caps for variables, happy to know I can go lower :D – treyBake Jun 5 '19 at 13:24
  • Yeah, it's weird - a lot of popular shell scripting resources contain various errors and stylistic problems. – tripleee Jun 5 '19 at 13:25
  • ah that's scary.. its like going through w3schools xD – treyBake Jun 5 '19 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.