我正在嘗試設定一個變數,該變數包含帶有前導零的值的字串表示形式。我知道我可以 printf 來終止值,并且可以將 printf 的字串輸出傳遞給變數。然而,似乎將值字串分配給一個新變數會重新解釋該值,如果我再列印它,該值就會丟失其前導零。
我們如何使用 bash 腳本中的變數來避免隱式型別推斷,以及最終如何獲得我正在尋找的解決方案。僅供參考,我正在尋找連接一個大的固定長度字串數字,比如零件號,并從較小的準備好的字串構建它。
更新:
事實證明變數的分配方式以某種方式改變了它們的解釋,見下文:
例子:
#!/bin/bash
a=3
b=4
aStr=$(printf d $a)
bStr=$(printf d $b)
echo $aStr$bStr
輸出
$ ./test.sh
003004
$
替代形式:
#!/bin/bash
((a = 3))
((b = 4))
((aStr = $(printf d $a)))
((bStr = $(printf d $b)))
echo $aStr$bStr
輸出
$ ./test.sh
34
$
uj5u.com熱心網友回復:
bash 變數型別怎么做
沒有變數型別。所有變數都是字串(型別)。變數存盤一個值(一個字串),但變數還有一些與之相關的附加魔法屬性。
有 Bash 陣列,但我認為變數是陣列是一個屬性。盡管如此,在任何情況下,每個陣列元素都包含一個字串。有一個“數字”變數declare -i var,但它是變數的屬性 - 在記憶體中,變數仍然是一個字串,只有在設定它時 Bash 檢查要設定的字串(仍然是一個字串!)是否是一個數字。
將值字串分配給新變數會重新解釋值
Bash 不會“解釋”賦值的值。
我們如何使用 bash 腳本中的變數來避免隱式型別推斷
沒有“型別推斷”。變數的型別不會改變 - 它包含一個字串。
變數的值會根據使用它的背景關系進行不同的擴展和轉換。例如$(...)洗掉尾隨換行符。最值得注意的是不帶引號的變數擴展會經歷分詞和檔案名擴展。
例子:
將代碼發布到 shellcheck 會導致:
Line 2:
a = 3
^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).
Line 3:
b = 4
^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).
Line 4:
aStr = $(printf d $a)
^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).
^-- SC2046 (warning): Quote this to prevent word splitting.
^-- SC2154 (warning): a is referenced but not assigned.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
aStr = $(printf d "$a")
Line 5:
bStr = $(printf d $b)
^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).
^-- SC2046 (warning): Quote this to prevent word splitting.
^-- SC2154 (warning): b is referenced but not assigned.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
bStr = $(printf d "$b")
Line 7:
echo $aStr$bStr
^-- SC2154 (warning): aStr is referenced but not assigned.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
^-- SC2154 (warning): bStr is referenced but not assigned.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
echo "$aStr""$bStr"
Shellcheck 告訴你什么是錯的。解決問題后:
#!/bin/bash
a=3
b=4
aStr=$(printf d "$a")
bStr=$(printf d "$b")
echo "$aStr$bStr"
執行后輸出您的預期輸出:
003004
uj5u.com熱心網友回復:
通過這樣做((aStr = $(printf d $a))),您將再次破壞由printf. 如果你做一個,你會看到同樣的效果
(( x = 005 ))
echo $x
哪個輸出5。
實際上,插入的零printf可能會損害您的號碼,如以下示例所示:
(( x = 015 ))
echo $x
輸出13,因為 將((....))前導零解釋為八進制數的指示。
因此,如果您有一個表示格式化(漂亮列印)數字的字串,請不要再在數字背景關系中使用此字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/520101.html
標籤:重击类型类型转换
上一篇:過濾的Windows命令在WSL中獨立作業,但不在腳本中
下一篇:如何將多個值插入json檔案?
