0

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
1
  • My answer here covers (in part) how to index individual characters out of a string in the shell. Commented Mar 11, 2015 at 22:51

1 Answer 1

0

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")'
Sign up to request clarification or add additional context in comments.

1 Comment

thank you this helped me access the different characters in the argument

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.