Search code examples
arraysstringbashposition

How would I convert an argument into a string in bash


When I run the script I enter a single argument. I want to store the argument into a variable and access it as a string. So if I enter $ ./script foo I should be able to access f, o, and o. So echo $pass[0] should display f

but what I am finding is that $pass is storing the argument as one piece so echo $pass[0] displays foo

How do I access the different positions in the string?

#!/bin/bash

all=( 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z )

pass=$1

max=${#pass}

for (( i=0; i<max; i++ ))
do
        for (( n=0; n<10; n++ ))
        do
                if [ "${pass[$i]}" == ${all[$n]} ]
                then
                echo true
                else
                echo false i:$i n:$n pass:${pass[$i]} all:${all[$n]}
                fi
        done
done

Solution

  • To spell out Etan's comment in the context of this question:

    set -- "my password"
    chars=()
    for ((i=0; i<${#1}; i++)); do chars+=("${1:i:1}"); done
    declare -p chars
    

    outputs

    declare -a chars='([0]="m" [1]="y" [2]=" " [3]="p" [4]="a" [5]="s" [6]="s" [7]="w" [8]="o" [9]="r" [10]="d")'