![如何將字串添加到數字中](https://rvso.com/image/1072602/%E5%A6%82%E4%BD%95%E5%B0%87%E5%AD%97%E4%B8%B2%E6%B7%BB%E5%8A%A0%E5%88%B0%E6%95%B8%E5%AD%97%E4%B8%AD.png)
我最近一直在嘗試創建一個可以將二進制數轉換為十進制數的腳本。這是我到目前為止所得到的:
#!/bin/bash
echo "Specify no of digits"
read digits
if [[ $digits == 1 ]]; then
echo "Enter 1 st digit"
read 1
elif [[ $digits == 2 ]]; then
echo "Enter 1 st digit"
read 1
echo "Enter 2 nd digit"
read 2
elif [[ $digits == 3 ]]; then
echo "Enter 1 st digit"
read 1
echo "Enter 2 nd digit"
read 2
echo "Enter 3 rd digit"
read 3
elif [[ $digits > 3 ]]; then
echo "Enter 1 st digit"
read 1
echo "Enter 2 nd digit"
read 2
echo "Enter 3 rd digit"
read 3
for digitno in {4..$digits};
do
echo "Enter $digitno th digit"
read $digitno
($nodigits++)
done
echo "$4"
else
echo "Please enter a valid no of digits. Type './binary_decoder.sh'"
exit 1
fi
我知道這是一個很長的劇本。但請嘗試花時間檢查這個腳本。
如果您查看 if 條件中的任何行read
,您將看到語句分配數字的變數read
本身就是數字。對於 Bash 語法,這是行不通的。我希望變數像 n1、n2、n3、n4... 等等。但是,如果您查看語句內部elif [[ $digits > 3 ]]; then
,您會發現有一個 for 循環,允許解碼無限的數字。現在,我不知道有什麼方法可以將字串添加n
到變數中的數字中$digitno
。但我想知道你們中是否有人能弄清楚如何將字串添加n
到$digitno
變數中。
任何幫助將不勝感激。
答案1
您可以使用簡單的串聯將字串新增至數字:
$ i=3
$ echo n$i
n3
然而,這對你真正的目標沒有多大幫助,這似乎是如何將不確定數量的使用者輸入分配給索引變量。
正如您已經發現的,您不能在命令中使用名為1
、2
等的變數。除了 bash 變數名稱至少必須3
read
開始帶有字母字元或底線的擴展$1
、$2
等$3
保留給 shell位置參數。
如果您確實想在腳本中使用$1
... ,實際上可以使用shell 內建命令來執行此操作。請注意,儘管 POSIX 只要求支援最多 的參數,但 bash 支援任意數量(儘管對於大於 9 的索引,您需要使用大括號來消除歧義,例如,作為第 10 個位置參數和與文字的串聯) 。例如:$n
set
$9
${10}
$10
$1
0
#!/bin/bash
set --
while : ; do
read -n1
case $REPLY in
[01]) set -- "$@" "$REPLY"
;;
*) break
;;
esac
done
for ((i=1; i<=$#; ++i)); do
printf 'Digit #%d = %d\n' "$i" "${!i}"
done
0
使用者輸入和字元序列1
,透過點擊任何其他字元(包括換行符)來終止該序列:
$ ./bin2dec
1011010110
Digit #1 = 1
Digit #2 = 0
Digit #3 = 1
Digit #4 = 1
Digit #5 = 0
Digit #6 = 1
Digit #7 = 0
Digit #8 = 1
Digit #9 = 1
Digit #10 = 0
或者,您可以對使用者定義的陣列執行基本上相同的操作:
#!/bin/bash
arr=()
while : ; do
read -n1
case $REPLY in
[01]) arr+=("$REPLY")
;;
*) break
;;
esac
done
for ((i=0; i<${#arr[@]}; ++i)); do
printf 'Digit #%d = %d\n' "$i" "${arr[i]}"
done
注意不同的索引;儘管兩個陣列都是從零開始的,但第 0 個元素$@
是為腳本檔案的名稱保留的。