我正在尝试扩展 Bash 变量。我已经搜索过,但不确定搜索词是什么来实现我想要做的事情。这是我的代码。两个问题:
- 如何获得如图所示的所需输出?
- 用于描述我想要的内容的 Bash 术语是什么?
# Set Library install directories
install_dir_1=~/Desktop/arduino-1.8.4
install_dir_2=~/Desktop/arduino-1.8.5
install_dir_3=~/Desktop/arduino-1.8.5a
x=0
while [ $x -lt 4 ]; do
let x=x+1
install_dir=install_dir_$x
#echo $install_dir
install_dir=$install_dir
#echo $install_dir
dir_Adafruit_SSD1306=$install_dir/libraries/Adafruit_SSD1306/
echo $dir_Adafruit_SSD1306
done
实际输出是
install_dir_1/libraries/Adafruit_SSD1306/
install_dir_2/libraries/Adafruit_SSD1306/
install_dir_3/libraries/Adafruit_SSD1306/
install_dir_4/libraries/Adafruit_SSD1306/
期望的输出是
~/Desktop/arduino-1.8.4/libraries/Adafruit_SSD1306/
~/Desktop/arduino-1.8.5/libraries/Adafruit_SSD1306/
~/Desktop/arduino-1.8.5a/libraries/Adafruit_SSD1306/
答案1
这称为取消引用变量,虽然可能,但在这里实际上没有必要。所以,是的,您可以使用相同的方法并使用取消引用,如下所示:
#!/bin/bash
# Set Library install directories
install_dir_1=~/Desktop/arduino-1.8.4
install_dir_2=~/Desktop/arduino-1.8.5
install_dir_3=~/Desktop/arduino-1.8.5a
x=1
while [ $x -lt 4 ]; do
## Set the instal_dir variable to point to the
## name of the variable you want to dereference
install_dir="install_dir_$x"
## Dereference the variable using the ${!var} notation
install_dir=${!install_dir}
dir_Adafruit_SSD1306="$install_dir/libraries/Adafruit_SSD1306/"
echo "$dir_Adafruit_SSD1306"
let x=x+1
done
但这确实太复杂了。这是一个执行相同操作的简化版本:
#!/bin/bash
install_dirs=("~/Desktop/arduino-1.8.4"
"~/Desktop/arduino-1.8.5"
"~/Desktop/arduino-1.8.5a")
for((x=0;x<${#install_dirs[@]};x++)); do
install_dir=${install_dirs[$x]}
echo "$install_dir"
done