Arrays 在bash中如何将参数转换为字符串
当我运行脚本时,我输入一个参数。我想将参数存储到变量中,并将其作为字符串访问。因此,如果我输入$/脚本foo,我应该能够访问f、o和o。所以echo$pass[0]应该显示f 但我发现$pass将参数存储为一个整体 所以echo$pass[0]显示foo 如何访问字符串中的不同位置Arrays 在bash中如何将参数转换为字符串,arrays,string,bash,position,Arrays,String,Bash,Position,当我运行脚本时,我输入一个参数。我想将参数存储到变量中,并将其作为字符串访问。因此,如果我输入$/脚本foo,我应该能够访问f、o和o。所以echo$pass[0]应该显示f 但我发现$pass将参数存储为一个整体 所以echo$pass[0]显示foo 如何访问字符串中的不同位置 #!/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
#!/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
在这个问题的背景下,阐述Etan的评论:
set -- "my password"
chars=()
for ((i=0; i<${#1}; i++)); do chars+=("${1:i:1}"); done
declare -p chars
我的回答部分介绍了如何从shell中的字符串中索引单个字符。谢谢,这帮助我访问参数中的不同字符
declare -a chars='([0]="m" [1]="y" [2]=" " [3]="p" [4]="a" [5]="s" [6]="s" [7]="w" [8]="o" [9]="r" [10]="d")'