在带有echo的bash数组中命名的每个函数的前缀?

时间:2016-10-04 00:47:02

标签: bash loops for-loop recursion terminal

我循环播放数组:

declare -a CommandArray
CommandArray[1]=check_homebrewinstall
CommandArray[2]=check_javainstall
CommandArray[3]=check_gitversioninstall

for i in "${!CommandArray[@]}"; do ${CommandArray[$i]}; done

打印哪些:

✓ Homebrew is installed at /usr/local/bin/brew.
✓ Java is installed at /usr/bin/java.
✓ Latest Git Version: 2.10.1

但是我需要添加到for循环才能打印?:

1) ✓ Homebrew is installed at /usr/local/bin/brew.
2) ✓ Java is installed at /usr/bin/java.
3) ✓ Latest Git Version: 2.10.1

我想在每个函数调用它之前对它们进行编号。

2 个答案:

答案 0 :(得分:1)

只需添加索引号${!CommandArray[$i]},您已将其保存为变量i,正确格式化输出字符串:

for i in "${!CommandArray[@]}"; do printf '%s) %s\n' "$i" "$( "${CommandArray[$i]}" )"; done
  • 命令替换"$( "${CommandArray[$i]}" )"运行扩展${CommandArray[$i]}作为命令

  • 使用printf模式'%s)%s \ n'以所需格式格式化输出,第一个字符串(数字)来自i ,以及命令替换中的第二个

答案 1 :(得分:1)

为了简洁起见,我考虑迭代值而不是键,并维护一个计数器:

for cmd in "${CommandArray[@]}"; do
  printf '%d) %s\n' "$(( ++idx ))" "$("$cmd")"
done

...或者,如果您信任每个命令发出一行,以换行符终止,则可以通过放弃命令替换并让正在执行的命令将其结果直接写入stdout文件描述符来提高效率它继承自调用它的脚本:

for cmd in "${CommandArray[@]}"; do
  printf '%d) ' "$(( ++idx ))"  # print number with no trailing newline
  "$cmd"                        # ...and count on the command to emit a newline
done