Lets say I have the following input in bash/linux
2
3
5
and I want to assign these lines to num1 num2 and num2 separately. How could I assign these variables? I know for sure it involves read but I don't know how to break apart what it reads.
Thanks!
CodePudding user response:
Since read
reads a line (by default), you want 3 separate read
commands:
read -r num1
read -r num2
read -r num3
You can read all the input into an array with the mapfile
command.
mapfile -t nums
# then
echo "first: ${nums[0]}"
echo "second: ${nums[1]}"
echo "third: ${nums[2]}"
CodePudding user response:
run in bash $
needname() { i=0; while read num$i; do x=num${i}; echo "${!x}"; if [[ -z ${num}$i ]]; then break; fi;((i )); done ; }
You can have a file (test.txt) with the content
Line1
Line2
Line3
And run
needname < test.txt
Or you can input it with a pipe
echo -en "line1\nline2\nline3\n"|needname
cat test.txt|needname
Or simply type them in by hand ending with a blank line
needname
Then > echo "$num0 $num1 etc"
You can put this function in a file script.sh and use it the same way