Note that there are some explanatory texts on larger screens.

plurals
  1. POBASH - Refer to parameters using variable
    primarykey
    data
    text
    <p>I was trying to make a small script that calculates a binary number to decimal. It works like this:</p> <p>-Gets '1' or '0' digits as SEPARATE parameters. e.g. "./bin2dec 1 0 0 0 1 1 1".</p> <p>-For each parameter digit: if it is '1', multiplies it with the corresponding power of 2 (in the above case, the most left '1' will be 64), then adds it in a 'sum' variable.</p> <p>Here's the code (it is wrong in the noted point):</p> <pre><code> #!/bin/bash p=$((2**($#-1))) #Finds the power of two for the first parameter. sum=0 #The sum variable, to be used for adding the powers of two in it. for (( i=1; i&lt;=$#; i++ )) #Counts all the way from 1, to the total number of parameters. do if [ $i -eq 1 ] # *THIS IS THE WRONG POINT* If parameter content equals '1'... then sum=$(($sum+$p)) #...add the current power of two in 'sum'. fi p=$(($p/2)) #Divides the power with 2, so to be used on the next parameter. done echo $sum #When finished show the 'sum' content, which is supposed to be the decimal equivalent. </code></pre> <p>My question is in the noted point (line #10, including blank lines). There, I’m trying to check if EACH parameter's content equals 1. How can I do this using a variable? </p> <p>For example, $1 is the first parameter, $2 is the 2nd and so on. I want it to be like $i, where 'i' is the variable that is increased by one each time so that it matches the next parameter.</p> <p>Among other things, I tried this: '$(echo "$"$i)' but didn't work.</p> <p>I know my question is complicated and I tried hard to make it as clear as I could. Any help?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload