簡體   English   中英

如何在數組中存儲連續數字,bash 腳本?

[英]How to store a continous number in array, bash scripting?

在數組中聲明和存儲一個數字很容易,但問題是用戶給出了輸入 1234,我想將這些數字存儲為 $array[0]=1, $array[1]=2, $array[2]= 3, $array[3]=4 但實際發生的是 $array[0]=1234, $array[1]=null, $array[2]=null, $array[3]=null。 我不知道如何分別存儲每個數字

#!/bin/bash
declare -a key
read -p "Enter the encryption key: " numbers
key=($numbers)
echo ${key[0]} 
echo ${key[1]}
echo ${key[2]}
echo ${key[3]}.

實際輸出:

輸入加密密鑰:1234

1234

空值

空值

空值

期望的輸出:

輸入加密密鑰:1234

1

2

3

4

先感謝您 :)

也有可能使用

key=(`grep -o . <<< "$numbers"`)

您可以使用子字符串表示法${string:initial_index:length_of_substring}訪問 $numbers 中的不同字母,而無需創建數組:

echo ${numbers:0:1}
echo ${numbers:1:1}
echo ${numbers:2:1}
echo ${numbers:3:1}

你可以試試。

declare -a key
read -p "Enter the encryption key: " numbers
while read -n1 input; do
  key+=("$input")
done < <(printf '%s' "$numbers")

printf '%s\n' "${key[@]}"

查看您如何使用read以便您已經假設密鑰中沒有空格,您可以這樣做:

#!/bin/bash
declare str
read -p "Enter the encryption key: " str

# replace each character with that character + space
spaced=$(echo "$str" | sed 's/\(.\)/\1 /g')

# without quotes, array elements will be each of the space-separated strings
numbers=( $spaced )

printf "array element %s\n" "${numbers[@]}"

輸出:

Enter the encryption key: hello123
array element h
array element e
array element l
array element l
array element o
array element 1
array element 2
array element 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM