0

I have asked way too many dumb questions here, but here we go.

Code:

#!/bin/bash

for i in {0..$#}; do
        ascii ${!i} | grep "\`" | tail -c 3 | head -c 1;
done
echo

(This is to translate long binary input, like from those horror games that have binary at the end)

Error message:

./asciit: line 4: {0..2}: invalid variable name

Command run:

./asciit 01101000 01101001

Why?

  • `for i in "$@"; do ascii "$i" ...` -- there's no reason to iterate over numbers at all. – Charles Duffy Sep 29 '22 at 23:38
  • 1
    The way-too-short explanation for why you can't use variables in `{x..y}` is that brace expansion happens **before** parameter expansion.. – Charles Duffy Sep 29 '22 at 23:39
  • See https://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash – John3136 Sep 29 '22 at 23:39
  • So what's happening here is that the range expression itself is going in `i` because it can't be expanded (for the order-of-operations reasons given above), and then when you use `${!i}` the shell tries to treat that expression like a variable name. – Charles Duffy Sep 29 '22 at 23:40
  • This is [BashPitfalls #33](https://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D). – Charles Duffy Sep 29 '22 at 23:40

0 Answers0