My text file is:
1 2000 4000 6000
2 3000 5000 7000
3 8000 9000 0000
.
.
.
or any information that the user will input
How can I show the full content of the text file with the dialog --checklist
, please?
The expected output:
[ ] 1 2000 4000 6000
[ ] 2 3000 5000 7000
[ ] 3 8000 9000 0000
.
.
.
.
CodePudding user response:
Use an array to store all the entries of the checklist (And the other arguments for it):
#!/usr/bin/env bash
# Initial arguments: header-text height width list-height
declare -a args=("Make your selection(s)" 20 70 20)
# Add each line to the checklist, using the first column as the tag
while read -r tag item; do
# tag item status
args =("$tag" "$item" off)
done < list.txt
# And display the dialog and capture the output
tmpfile=$(mktemp)
dialog --separate-output --checklist "${args[@]}" 2>"$tmpfile"
readarray -t selected <"$tmpfile"
rm -f -- "$tmpfile"
# And show the user what they picked
printf "Your selections: "
printf "%s " "${selected[@]}"
printf "\n"
CodePudding user response:
Try this:
#!/bin/bash
datafile="list.txt"
# Check if the file exists
if [[ ! -f "$datafile" ]]
then
echo "ERROR: file >>$datafile<< does not exist."
exit 1
fi
choices="dialog --checklist \"Title\" 20 100 100 "
# Read the file line per line
while IFS= read -r line
do
# skip empty lines
if [[ "$line" == "" ]]
then
continue
fi
# first element of the line is the id
idnumber=${line%% *}
# keep the rest of the line, without the id, and add quotes
restofline="'$(echo "$line" | cut -d' ' -f2-)'"
# Add these to the choices
choices="$choices $idnumber $restofline off"
done < "$datafile"
# DEBUG echo ">>$choices<<"
eval $choices
dialog
expects:<Title> <height> <width> <list height> <tag1> <item1> <status1> <tag2> <item2> <status2> ...
status can be
on
oroff
, to specify whether that tag is to be selected or not when the dialog is created. Here it is setoff
by default.in your data, you have
1 2000 4000 6000
. Therefore the tag is the first element (here 1) and the rest are the item (here "2000 4000 6000").to allow many words in the item, you must enclose them in quotes.
this explains why I extract the first word in the line for the tag, and the rest are surrounded by quotes.
each line in list.txt is transformed into another dialog tag-item-status element.
Obviously you will have to play with the parameters and title to configure
dialog
like you need it.