I would like to take a specific line from a variable to another variable. I tried this but it doesn't work:
c="1.apple
2.banna
3.peach"
read "Please choose fruit [1-3]:" t
a=$c | awk "NR==$t"
echo "You choose: $a"
What is my mistake?
I would like to take a specific line from a variable to another variable. I tried this but it doesn't work:
What is my mistake? |
||||
Use Here String redirection
|
|||||||||
|
In the first place:
...will not work. It looks like you're trying to provide a prompt string to the shell builtin
...is an option supported in many shells and is probably nearer to what you intend to do. That said, you probably shouldn't stack multiple values in a singly delimited assignment unless you have previously settled on a means splitting it out. When you do:
The shell will eventually parse that out to something like:
...and assign the single name to the single value. Many shells offer more advance forms of delimiting - such as named arrays - but all POSIX shells provide at least one easily definable array per function context - the So rather than assigning all of those individual values to a single string as you do, you might do instead:
You can witness the effect of this by addressing each individual value singly by number like:
...which prints:
Note - if you get to using values larger than 9 it is best to enclose the reference in braces like You can address the number of different strings in
...which prints...
You can address the lot of them in a list of separate strings like:
...which prints:
...or as a single, concatenated string like:
...where the separate array value strings are concatenated on the first character contained in the shell variable
...but if I do:
...it prints:
Most shells that implement named array extensions do so with similar syntax, excepting that the various means of addressing the array must be associated with a name. An array assignment typically looks like:
...or...
Compared to Once you have properly delimited your values your problem becomes a much easier one to handle:
Some may scoff at the use of |
||||
|
-p
inread
? – BroSlow Jan 18 at 8:59