首页 > 解决方案 > bash - 从列表中选择一个数字并打印特定的输出

问题描述

我制作了一个脚本,要求您输入一个字符串,然后您需要从列表中选择一个数字,如果您实际选择了一个数字,程序将打印该字符串,但带有样式和您需要编写的内容才能应用您为字符串选择的样式(下面的代码)有什么方法可以使它更短吗?(特别是 if 和 elif 语句)

#!/bin/bash
clear
echo "Hello, who am I talking to?"
# Get string from user input
read -p 'String: ' string
echo $string
echo "Please select a modifier from this list by typing the modifier\'s number."
# List possible styles that can be applied to the string
printf '\e[1;4;33m[1] Bold string\n'
printf '\e[4;33m[2] Underlined string\n\e[0;33m'
printf '\e[30;47m[3] Black foreground\n\e[0;33m'
printf '\e[31;47m[4] Red foreground\n'
printf '\e[32m[5] Green foreground\n'
printf '\e[33m[6] Yellow foreground\n'
printf '\e[34m[7] Blue foreground\n'
printf '\e[35m[8] Purple foreground\n'
printf '\e[36m[9] Cyan foreground\n'
printf '\e[0;37;40m[10] White foreground\n\e[0;33m'
printf '\e[1;4;33m[11] Black background\n'
printf '\e[1;4;33m[12] Red background\n'
printf '\e[1;4;33m[13] Green background\n'
printf '\e[1;4;33m[14] Yellow background\n'
printf '\e[1;4;33m[15] Blue background\n'
printf '\e[1;4;33m[16] Purple background\n'
printf '\e[1;4;33m[17] Cyan background\n'
printf '\e[1;4;33m[18] White background\n\e[0;37m'
# Ask user to choose a style to apply
read -p 'Number: ' number
# Check if the number is between 1 and 18
if ! [[ $number =~ ^([1-9]|1[018])$ ]]
then
        echo 'Please only select a number from 1 to 18'
fi
# If the number that the user chose is 1, print a bold string
if [[ $number = 1 ]]
then
        printf "\e[1;37m${string}\n"
        echo "\e[1;37m${string}\n"
elif [[ $number = 2 ]]
then
        printf "\e[4;37m${string}\n"
        echo "\e[4;37m${string}\n"
#(etc.)

标签: bashprintf

解决方案


您可以将代码和颜色名称存储在数组中,然后只需使用循环对其进行迭代。

#!/bin/bash
clear

colors=("",
        'Bold string'
        'Underlined string'
        'Black foreground'
        'Red foreground'
        'Green foreground'
        'Yellow foreground'
        'Blue foreground'
        'Purple foreground'
        'Cyan foreground'
        'White foreground'
        'Black background'
        'Red background'
        'Green background'
        'Yellow background'
        'Blue background'
        'Purple background'
        'Cyan background'
        'White background')
codes=("", '1' '4' '30;47' '31' '32' '33' '34' '35' '36' '0;37;40' '39' '41'
       '42' '43' '44' '45' '46' '47')

read -p 'Hello, who am I talking to? ' string
echo "Hello, $string!"
echo "Please select a modifier from this list by typing the modifier's number."

for i in {1..18} ; do
    printf '\e[%sm[%d] %s\e[m\n' "${codes[i]}" $i "${colors[i]}"
done;

read -p 'Your choice? (number) ' number
if ! [[ $number =~ ^([1-9]|1[0-8])$ ]]
then
        echo 'Please only select a number from 1 to 18'
else
    printf '\e[%sm%s\e[m\n' "${codes[number]}" "$string"
fi

我所做的其他更改:

  • 使用提示来提问
  • 打印后关闭颜色
  • 无需在双引号内反斜杠单引号
  • 检查号码的正则表达式错误,我修复了它。

推荐阅读