Home > Blockchain >  Echo name not a number in case (choice). #bash
Echo name not a number in case (choice). #bash

Time:10-18

I need to echo - the choice - from the case to a csv file. When I echo varSel from below, I'm getting only the number and I want the "name" (sale or return in this case). The while loop is here only to make to narrow user's choice. It's part of a bigger script, but as of now I only need this part to work, anything else does.

#! /bin/bash


while true; do
    echo    "1) sale"
    echo    "2) return"
    

    read -p "Choose your options: " varSel
    case ${varSel} in
    1) var1="sale"; break;;
    2) var1="return"; break;;
    *) echo "Choose options between 1 and 2";;
    esac
done

echo $varSel >> logfile.csv

CodePudding user response:

As another user already mentioned in the comments, you should echo "$var1" >> logfile.csv instead of echo $varSel >> logfile.csv in the last line of your script.


Another, more elaborate way would be to use an array containing possible choices as a basis to drive everything else (to illustrate, I added a few more choices):

#!/bin/bash

choices=("sale" "return" "somethingelse" "hello" "world")

while true; do

    # List possible choices
    for ((i=0; i < ${#choices[@]}; i  )); do
        echo "$((i 1))) ${choices[i]}"
    done

    # Prompt user to choose
    read -p "Choose your options: " varSel

    # Check if choice is valid, break loop if so
    # (varSel needs to be: non-empty, an integer and within range of possible choices)
    if [[ "${varSel}" != "" && "${varSel}" != *[!0-9]* ]] && (( ${varSel} >= 1 && ${varSel} <= ${#choices[@]} )); then
        choice="${choices[varSel-1]}"
        break
    else
        echo "Choose options between 1 and ${#choices[@]}"
    fi

done

echo "${choice}" >> logfile.csv

This can be used as a general template for any number of choices. The one tricky thing here is to keep track of choice numbers vs. array indices (choices are 1..n, array indices are 0..n-1).

CodePudding user response:

You're reinventing the builtin select command:

#!/usr/bin/env bash
PS3="Choose your options: "
select choice in sale return; do
    [[ -n $choice ]] && break
done
echo "$choice" >> logfile.csv
  • Related