bash select multiple answers at once - bash

I have a flat file called items that I want to populate a select but I want to be able to choose multiple items at one time.
contents of items file:
cat 1
dog 1
pig 1
cherry 2
apple 2
Basic script:
#!/bin/bash
PS3=$'\n\nSelect the animals you like: '
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }')
select choice in $options
do
echo "you selected: $choice"
done
exit 0
The way it flows now is I can only select one option at at time. I'd like to be able to answer 1,3 or 1 3 and have it respond "you selected: cat pig"
Thank you,
Tazmarine

I can offer a somewhat different approach that uses a different selection prompt style. Here's a bash function that allows user to select multiple options with arrow keys and Space, and confirm with Enter. It has a nice menu-like feel. I wrote it with the help of https://unix.stackexchange.com/a/415155. It can be called like this:
multiselect result "Option 1;Option 2;Option 3" "true;;true"
The result is stored as an array in a variable with the name supplied as the first argument. Last argument is optional and is used for making some options selected by default. It looks like this:
function prompt_for_multiselect {
# little helpers for terminal print control and key input
ESC=$( printf "\033")
cursor_blink_on() { printf "$ESC[?25h"; }
cursor_blink_off() { printf "$ESC[?25l"; }
cursor_to() { printf "$ESC[$1;${2:-1}H"; }
print_inactive() { printf "$2 $1 "; }
print_active() { printf "$2 $ESC[7m $1 $ESC[27m"; }
get_cursor_row() { IFS=';' read -sdR -p $'\E[6n' ROW COL; echo ${ROW#*[}; }
key_input() {
local key
IFS= read -rsn1 key 2>/dev/null >&2
if [[ $key = "" ]]; then echo enter; fi;
if [[ $key = $'\x20' ]]; then echo space; fi;
if [[ $key = $'\x1b' ]]; then
read -rsn2 key
if [[ $key = [A ]]; then echo up; fi;
if [[ $key = [B ]]; then echo down; fi;
fi
}
toggle_option() {
local arr_name=$1
eval "local arr=(\"\${${arr_name}[#]}\")"
local option=$2
if [[ ${arr[option]} == true ]]; then
arr[option]=
else
arr[option]=true
fi
eval $arr_name='("${arr[#]}")'
}
local retval=$1
local options
local defaults
IFS=';' read -r -a options <<< "$2"
if [[ -z $3 ]]; then
defaults=()
else
IFS=';' read -r -a defaults <<< "$3"
fi
local selected=()
for ((i=0; i<${#options[#]}; i++)); do
selected+=("${defaults[i]}")
printf "\n"
done
# determine current screen position for overwriting the options
local lastrow=`get_cursor_row`
local startrow=$(($lastrow - ${#options[#]}))
# ensure cursor and input echoing back on upon a ctrl+c during read -s
trap "cursor_blink_on; stty echo; printf '\n'; exit" 2
cursor_blink_off
local active=0
while true; do
# print options by overwriting the last lines
local idx=0
for option in "${options[#]}"; do
local prefix="[ ]"
if [[ ${selected[idx]} == true ]]; then
prefix="[x]"
fi
cursor_to $(($startrow + $idx))
if [ $idx -eq $active ]; then
print_active "$option" "$prefix"
else
print_inactive "$option" "$prefix"
fi
((idx++))
done
# user key control
case `key_input` in
space) toggle_option selected $active;;
enter) break;;
up) ((active--));
if [ $active -lt 0 ]; then active=$((${#options[#]} - 1)); fi;;
down) ((active++));
if [ $active -ge ${#options[#]} ]; then active=0; fi;;
esac
done
# cursor position back to normal
cursor_to $lastrow
printf "\n"
cursor_blink_on
eval $retval='("${selected[#]}")'
}

You can not do that as such, but you can always record each individual selection:
#!/bin/bash
PS3=$'\n\nSelect the animals you like: '
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }')
# Array for storing the user's choices
choices=()
select choice in $options Finished
do
# Stop choosing on this option
[[ $choice = Finished ]] && break
# Append the choice to the array
choices+=( "$choice" )
echo "$choice, got it. Any others?"
done
# Write out each choice
printf "You selected the following: "
for choice in "${choices[#]}"
do
printf "%s " "$choice"
done
printf '\n'
exit 0
Here's an example interaction:
$ ./myscript
1) cat
2) dog
3) pig
4) Finished
Select the animals you like: 3
pig, got it. Any others?
Select the animals you like: 1
cat, got it. Any others?
Select the animals you like: 4
You selected the following: pig cat
If you instead want to be able to write 3 1 on the same line, you'll have to make your own menu loop with echo and read

This is what I came up with. This seems to works as I want. I want the final output to be comma separated:
#!/bin/bash
newarray=(all $(grep '1' items|grep -v '^#' |awk '{ print $1 }'))
options() {
num=0
for i in ${newarray[#]}; do
echo "$num) $i"
((num++))
done
}
getanimal() {
while [[ "$show_clean" =~ [A-Za-z] || -z "$show_clean" ]]; do
echo "What animal do you like: "
options
read -p 'Enter number: ' show
echo
show_clean=$(echo $show|sed 's/[,.:;]/ /g')
selected=$(\
for s in $show_clean; do
echo -n "\${newarray[${s}]},"
done)
selected_clean=$(echo $selected|sed 's/,$//')
done
eval echo "You selected $selected_clean"
}
getanimal
exit 0

Related

What is the best way to accept a 2nd user input from options defined by the 1st user input?

My background is in SQL but I've been learning Bash to create tools to help non-Linux users find what they need from my Linux system - I am pretty green with Bash, I apologize if this looks a bit dumb.
The goal of the script is to essentially display all directories within the current directory to the user, and allow them to input 1-9 to navigate to lower directories.
My sticking point is that I'm trying to use arrays to define potential filepaths, since in practice new directories will be added over time and it is not practical to edit the script each time a filepath is added.
Here's my prototype so far, currently it navigates into Test1, Test2, or Test3 then echos pwd to prove it is there.
#Global Variables
DIR_MAIN='/home/admin/Testhome'
#Potential Filepaths
#/home/admin/Testhome/Test1/Test1-1/
#/home/admin/Testhome/Test1/Test1-2/
#/home/admin/Testhome/Test2/Test2-1/
#/home/admin/Testhome/Test2/Test2-2/
#/home/admin/Testhome/Test3/Test3-1/
#/home/admin/Testhome/Test3/Test3-2/
#Defining Array for first user input
arr=($(ls $DIR_MAIN))
#System to count total number of directories in filepath, then present to user for numbered selection
cnt=0
for i in ${arr[#]}
do
cnt=$(($cnt+1))
echo "$cnt) $i"
done
read -p "Select a folder from the list: " answer
case $answer in
1)
cd $DIR_MAIN/${arr[0]}
echo "Welcome to $(pwd)"
;;
2)
cd $DIR_MAIN/${arr[1]}
echo "Welcome to $(pwd)"
;;
3)
cd $DIR_MAIN/${arr[2]}
echo "Welcome to $(pwd)"
;;
esac
I've tried the following, but it doesn't like the syntax (to someone experienced I'm sure these case statements look like a grenade went off in vim).
I'm beginning to wonder if the SELECT CASE road I'm going down is appropriate, or if there is an entirely better way.
#User Input Start
echo "What is the secret number?"
while :
do
read STRING1
case $STRING1 in
1)
echo "Enter the number matching the directory you want and I will go there"
echo "1 - ${arr[0]}"
echo "2 - ${arr[1]}"
echo "3 - ${arr[2]}"
read STRING2
case $STRING2 in
1)
cd $DIR_MAIN/${arr[0]}
echo "Welcome to" $(pwd)
2)
cd $DIR_MAIN/${arr[1]}
echo "Welcome to" $(pwd)
3)
cd $DIR_MAIN/${arr[2]}
echo "Welcome to" $(pwd)
*)
echo "Thats not an option and you know it"
*)
echo "1 is the secret number, enter 1 or nothing will happen"
;;
esac
#break needs to be down here somewhere
done
Ultimately I know I'll need to variabilize a local array once I'm in Test2 for example (since in practice, this could descend as far as /Test2/Test2-9 and there would be tons of redundant code to account for this manually).
For now, I'm just looking for the best way to present the /Test2-1 and /Test2-2 filepaths to the user and allow them to make that selection after navigating to /Test2/
This might do what you wanted.
#!/usr/bin/env bash
shopt -s nullglob
n=1
for i in /home/admin/Testhome/Test[0-9]*/*; do
printf '%d) %s\n' "$n" "$i"
array[n]="$i"
((n++))
done
(( ${#array[*]} )) || {
printf 'It looks like there is/are no directory listed!\n' >&2
printf 'Please check if the directories in question exists!\n' >&2
return 1
}
dir_pattern_indices=$(IFS='|'; printf '%s' "#(${!array[*]})")
printf '\n'
read -rp "Select a folder from the list: " answer
if [[ -z $answer ]]; then
printf 'Please select a number and try again!' >&2
exit 1
elif [[ $answer != $dir_pattern_indices ]]; then
printf 'Invalid option %s\n' "$answer" >&2
exit 1
fi
for j in "${!array[#]}"; do
if [[ $answer == "$j" ]]; then
cd "${array[j]}" || exit
printf 'Welcome to %s\n' "$(pwd)"
break
fi
done
The script needs to be sourced e.g.
source ./myscript
because of the cd command. See Why can't I change directory using a script.
Using a function instead of a script.
Let's just name the function list_dir
list_dir() {
shopt -s nullglob
declare -a array
local answer dir_pattern_indices i j n
n=1
for i in /home/admin/Testhome/Test[0-9]*/*; do
printf '%d) %s\n' "$n" "$i"
array[n]="$i"
((n++))
done
(( ${#array[*]} )) || {
printf 'It looks like there is/are no directory listed!\n' >&2
printf 'Please check if the directories in question exists!\n' >&2
return 1
}
dir_pattern_indices=$(IFS='|'; printf '%s' "#(${!array[*]})")
printf '\n'
read -rp "Select a folder from the list: " answer
if [[ -z $answer ]]; then
printf 'Please select a number and try again!' >&2
return 1
elif [[ $answer != $dir_pattern_indices ]]; then
printf 'Invalid option %s\n' "$answer" >&2
return 1
fi
for j in "${!array[#]}"; do
if [[ $answer == "$j" ]]; then
cd "${array[j]}" || return
printf 'Welcome to %s\n' "$(pwd)"
break
fi
done
}
All of the array names and variables are declared local to the function in order not to pollute the interactive/enviromental shell variables.
Put that somewhere in your shellrc file, like say in ~/.bashrc then source it again after you have edited that shellrc file.
source ~/.bashrc
Then just call the function name.
list_dir
I took what #Jetchisel wrote and ran with it - I see they updated their code as well.
Between that code and what I hacked together piggybacking off what he wrote, I'm hoping future viewers will have what they need to solve this problem!
My code includes a generic logging function (can write to a log file if you define it and uncomment those logging lines, for a script this size I just use it to output debugging messages), everything below is the sequence used.
As he mentioned the "0" element needs to be removed from the array for this to behave as expected, as a quick hack I ended up assigning array element 0 as null and adding logic to ignore null.
This will also pull pretty much anything in the filepath, not just directories, so more tweaking may be required for future uses but this serves the role I need it for!
Thank you again #Jetchisel !
#hopt -s nullglob
DIR_MAIN='/home/admin/Testhome'
Dir_Cur="$DIR_MAIN"
LOG_LEVEL=1
array=(NULL $(ls $DIR_MAIN))
########FUNCTION LIST#########
####Generic Logging Function
Log_Message()
{
local logLevel=$1
local logMessage=$2
local logDebug=$3
local dt=$(date "+%Y-%m-%d %T")
##Check log level
if [ "$logLevel" == 5 ]
then local logLabel='INFO'
elif [ "$logLevel" == 1 ]
then local logLabel='DEBUG'
elif [ "$logLevel" == 2 ]
then local logLabel='INFO'
elif [ "$logLevel" == 3 ]
then local logLabel='WARN'
elif [ "$logLevel" == 4 ]
then local logLabel='ERROR'
fi
##Check conf log level
if [ "$LOG_LEVEL" == 1 ]
then #echo "$dt [$logLabel] $logMessage" >> $LOG_FILE ##Log Message
echo "$dt [$logLabel] $logMessage" ##Echo Message to Terminal
##Check if Debug Empty
if [ "$logDebug" != "" ]
then #echo "$dt [DEBUG] $logDebug" >> $LOG_FILE ##Extra Debug Info
echo "$dt [DEBUG] $logDebug" ##Extra Debug Info
fi
elif [ "$logLevel" -ge "$LOG_LEVEL" ]
then #echo "$dt [$logLabel] $logMessage" >> "$LOG_FILE" ##Log Message
echo "$dt [$logLabel] $logMessage"
fi
}
####
####Function_One
##Removes 0 position in array by marking it null, generates [1-X] list with further filepaths
Function_One()
{
Log_Message "1" "entered Function_One"
local local_array=("$#")
Log_Message "1" "${local_array[*]}"
n=1
for i in "${local_array[#]}"; do
if [ "$i" != "NULL" ]
then
printf '%d) %s\n' "$n" "$i"
array[n]="$i"
((n++))
fi
done
printf '\n'
read -rp "Select a folder from the list: " answer
for j in "${!local_array[#]}"; do
if [[ $answer == "$j" ]]; then
cd "$Dir_Cur/${local_array[j]}" || exit
printf 'Welcome to %s\n' "$(pwd)"
break
fi
done
}
####
########FUNCTION LIST END#########
########MAIN SEQUENCE########
echo "Script start"
Function_One "${array[#]}"
Dir_Cur="$(pwd)"
array2=(NULL $(ls $Dir_Cur))
Function_One "${array2[#]}"
Dir_Cur="$(pwd)"
$Dir_Cur/test_success.sh
echo "Script end"
########

Bash script - Using spaces as string

I'm trying to build a really simple TODO list with a bash script. It should allow user to add and remove a task and also see the entire list.
I've done it with the following script. But I've issues allowing a given task to take a whitespace as a string. For instance, if I'm adding a task with the command: ./programme_stack.sh add 1 start projet n1, it will only add a task with "start".
I've read a couple of things online, I know, I should double quote the variables but after trying this, it doesn't work. I must be missing something on the road.
Here is my script:
#!/bin/bash
TACHES=$HOME/.todo_list
# functions
function remove() {
res_remove=$(sed -n "$1p" $TACHES)
sed -i "$1d" $TACHES
}
function list() {
nl $TACHES
}
function add() {
if [ ""$(($(wc -l $TACHES | cut -d " " -f 1) + 1))"" == "$1" ]
then
echo "- $2" >> $TACHES
else
sed -i "$1i - $2" $TACHES
fi
echo "Task \"$2\" has been add to the index $1"
}
function isNumber() {
re='^[0-9]+$'
if ! [[ $# =~ $re ]] ; then
res_isNumber=true
else
res_isNumber=false
fi
}
# application
case $1 in
list)
list
;;
done)
shift
isNumber $#
if ! [[ "$res_isNumber" = false ]] ; then
echo "done must be followed by an index number"
else
nb_taches=$(wc -l $TACHES | cut -d " " -f 1)
if [ "$1" -ge 1 ] && [ "$1" -le $nb_taches ]; then
remove $1
echo "Well done! Task $i ($res_remove) is completed"
else
echo "this task doesn't exists"
fi
fi
;;
add)
shift
isNumber $1
if ! [[ "$res_isNumber" = false ]] ; then
echo "add must be followed by an index number"
else
index_max=$(($(wc -l $TACHES | cut -d " " -f 1) + 1))
if [ "$1" -ge 1 ] && [ "$1" -le $index_max ]; then
add $1 $2
else
echo "Idex must be between 1 and $index_max"
fi
fi
;;
*)
echo "./programme_stack.sh (list|add|done) [args]"
;;
esac
Can you guys see what I'm missing?
Many thanks!!
To get the script to support embedded spaces, 2 changes are needed
1) Accept embedded space - either
1A) Pass in the task name in quote script add nnn "say hello", OR
1B) Concatenate all the input parameters into single string.
2) Quote the task name to prevent it from being broken into individual words
In the code, implement 1B and 2
add)
...
if [ "$1" -ge 1 ] && [ "$1" -le $index_max ]; then
num=$1
shift
# Combine all remaining arguments
todo="$#"
add "$num" "$todo"
...

Nesting If Condition Inside A While Loop

I'm reading the contents of a file and storing them in 2 variables then simultaneously want to compare it with an array using if statement. Code is given below
#!/bin/bash
# Define File
datafile=./regions-with-keys
# Create Nodes File
cat << EOF > $datafile
region1 key1
region2 key2
region3 key3
EOF
# User Input
clear;
echo -ne "PLEASE SELECT REGIONS(s) :\n\033[37;40m[Minimum 1 Region Required]\033[0m"
read -ra a
echo "${a[#]}"
# Reading Regions & Keys
for i in "${a[#]}"
do
while read -r $b $c; do
if [ "${a[#]}" -eq "$b" ]; then
echo "$b" "$c"
fi
done < $datafile
done;
it gives command not found for if statement when executed..
Aim of the code is to match the array indexes of userinput with $a from $datafile, if match is successful print
$b and $c
Try this Shellcheck-clean code:
#!/bin/bash -p
# Define File
datafile=./regions-with-keys
# Create Nodes File
cat <<EOF >"$datafile"
region1 key1
region2 key2
region3 key3
EOF
# User Input
clear
echo 'PLEASE SELECT REGIONS(s) :'
echo -ne '\e[37;40m[Minimum 1 Region Required]\e[0m'
read -ra input_regions
declare -p input_regions
# Reading Regions & Keys
for input_rgn in "${input_regions[#]}" ; do
while read -r data_rgn key ; do
if [[ $data_rgn == "$input_rgn" ]] ; then
printf '%s %s\n' "$data_rgn" "$key"
fi
done <"$datafile"
done
Significant changes from the code in the question are:
Use meaningful variable names.
Use declare -p input_regions to print the contents of the array in an unambiguous way.
Use varname instead of $varname as arguments to read. That fixes a serious bug in the original code.
Use printf instead of echo for printing variable values. See Why is printf better than echo?.
Used [[ ... == ...]] instead of [ ... -eq ... ] for comparing the region names. [[ ... ]] is more powerful than [ ... ]. See Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?. Also, -eq is for comparing integers and == (or, equivalently, =) is for comparing strings.
Did various cleanups (removed some blank lines, removed unnecessary semicolons, ...).
The new code is Shellcheck-clean. Shellcheck identified several problems with the original code.
If you want to report incorrect input regions, try replacing the "Reading Regions & Keys" code with this:
for input_rgn in "${input_regions[#]}" ; do
# Find the key corresponding to $input_rgn
key=
while read -r data_rgn data_key ; do
[[ $data_rgn == "$input_rgn" ]] && key=$data_key && break
done <"$datafile"
if [[ -n $key ]] ; then
printf '%s %s\n' "$input_rgn" "$key"
else
printf "error: region '%s' not found\\n" "$input_rgn" >&2
fi
done

How can I make this multi-select Bash script default to all items selected?

I modified a great script I found online by Nathan Davieau on serverfault.com, but I have hit the limit to my knowledge of Bash!
It works great, apart from I have to select each item, I want it to start with all items selected and have to deselect them.
#!/bin/bash
ERROR=" "
declare -a install
declare -a options=('php' 'phpmyadmin' 'php-mysqlnd' 'php-opcache' 'mariadb-server' 'sendmail')
#=== FUNCTION ========================================================================
# NAME: ACTIONS
# DESCRIPTION: Actions to take based on selection
# PARAMETER 1:
#=======================================================================================
function ACTIONS() {
for ((i = 0; i < ${#options[*]}; i++)); do
if [[ "${choices[i]}" == "+" ]]; then
install+=(${options[i]})
fi
done
echo "${install[#]}"
}
#=== FUNCTION ========================================================================
# NAME: MENU
# DESCRIPTION: Ask for user input to toggle the name of the plugins to be installed
# PARAMETER 1:
#=======================================================================================
function MENU() {
echo "Which packages would you like to be installed?"
echo
for NUM in "${!options[#]}"; do
echo "[""${choices[NUM]:- }""]" $((NUM + 1))") ${options[NUM]}"
done
echo "$ERROR"
}
#Clear screen for menu
clear
#Menu loop
while MENU && read -e -p "Select the desired options using their number (again to uncheck, ENTER when done): " -n2 SELECTION && [[ -n "$SELECTION" ]]; do
clear
if [[ "$SELECTION" == *[[:digit:]]* && $SELECTION -ge 1 && $SELECTION -le ${#options[#]} ]]; then
((SELECTION--))
if [[ "${choices[SELECTION]}" == "+" ]]; then
choices[SELECTION]=""
else
choices[SELECTION]="+"
fi
ERROR=" "
else
ERROR="Invalid option: $SELECTION"
fi
done
ACTIONS
Here you go, you only need to initialize the choices[] (array) before you actually process them. (re-)Revised code below (with thanks to Charles Duffy) :
#!/bin/bash
ERROR=" "
declare -a install
declare -a options=('php' 'phpmyadmin' 'php-mysqlnd' 'php-opcache' 'mariadb-server' 'sendmail')
############### HERE's THE NEW BIT #################
declare -a choices=( "${options[#]//*/+}" )
####################################################
#=== FUNCTION ========================================================================
# NAME: ACTIONS
# DESCRIPTION: Actions to take based on selection
# PARAMETER 1:
#=======================================================================================
function ACTIONS() {
for ((i = 0; i < ${#options[*]}; i++)); do
if [[ "${choices[i]}" == "+" ]]; then
install+=(${options[i]})
fi
done
echo "${install[#]}"
}
#=== FUNCTION ========================================================================
# NAME: MENU
# DESCRIPTION: Ask for user input to toggle the name of the plugins to be installed
# PARAMETER 1:
#=======================================================================================
function MENU() {
echo "Which packages would you like to be installed?"
echo
for NUM in "${!options[#]}"; do
echo "[""${choices[NUM]:- }""]" $((NUM + 1))") ${options[NUM]}"
done
echo "$ERROR"
}
#Clear screen for menu
clear
#Menu loop
while MENU && read -e -p "Select the desired options using their number (again to uncheck, ENTER when done): " -n2 SELECTION && [[ -n "$SELECTION" ]]; do
clear
if [[ "$SELECTION" == *[[:digit:]]* && $SELECTION -ge 1 && $SELECTION -le ${#options[#]} ]]; then
((SELECTION--))
if [[ "${choices[SELECTION]}" == "+" ]]; then
choices[SELECTION]=""
else
choices[SELECTION]="+"
fi
ERROR=" "
else
ERROR="Invalid option: $SELECTION"
fi
done
ACTIONS
Sorry, but I can't afford the time to give a blow by blow description of how all this works. In this case, the traditional shell debugging tool of set -vx (paired with set +vx) might be a challenge to interpret for a newbie. Experiment only when you can spare the time.
Note that the key bit of code is where the + gets toggled :
if [[ "${choices[SELECTION]}" == "+" ]]; then
choices[SELECTION]=""
else
choices[SELECTION]="+"
fi
IHTH

sign automatic number to my file in bash

I am trying to assign a unique number to my strings that are redirected and stored in a file.
You have to fill in a form, and I want to send a unique number with it.
example:
echo fill in the form
echo place
read place
date
"place: $place, time $(date) >> List
It has to look something like this.
outcome in List
number 1, place, time
number 2, place, time
number 3, place, time
I used a loop but I got the following outcome.
number 0, place, time
number 0, place, time.
I think I need a function that checks the last number given in the file and add 1 to it, but I wonder if there is an easier way.
Perhaps this one:
#!/bin/bash
# Optionally truncate file
# : > List
I=0
while
read -p "Place: " PLACE
read -p "Time: " TIME
echo "number $((++I)), $PLACE, $TIME" >> List
read -n 1 -p "Continue? " && [[ $REPLY == [yY] ]]
do
continue
done
Update:
#!/bin/bash
# Optionally truncate file
# : > List
shopt -s extglob
for (( I = 1;; ++I )); do
for (( ;; )); do
read -p "Place: " PLACE
read -p "Time: " TIME
until
read -p "Save data? "
[[ $REPLY == [nN]?([oO]) ]]
do
[[ $REPLY == [yY]?([eE][sS]) ]] && break 2
echo "Please answer Y[es] or N[o]."
done
done
echo "Saving \"number $I, $PLACE, $TIME\"."
echo "number $I, $PLACE, $TIME" >> List
until
read -p "Continue? "
[[ $REPLY == [yY]?([eE][sS]) ]]
do
[[ $REPLY == [nN]?([oO]) ]] && break 2
echo "Please answer Y[es] or N[o]."
done
echo
done
To generate a 16-char random hex string, you can use r=$(openssl rand -hex 8)
To find the last number used and increment it, you can do
prev=$(awk -F, 'END {print $1}' List)
printf "%d, place:%s, time:%s\n" $((prev+1)) "$place" "$(date)" >> List
This is subject to a race condition if the script can be executed simultaneously
To start at 1:
if [[ ! -f List ]]; then
prev=1
else
prev=$(awk -F, 'END {print $1}' List)
fi
printf "%d, place:%s, time:%s\n" $((prev+1)) "$place" "$(date)" >> List

Resources