Here's what I got:
function stdin2var
set a (cat -)
echo $a
end
First example:
$ echo 'some text' | stdin2var
# should output "some text"
Second example:
$ echo some text\nsome more text | stdin2var
# should output: "some text
some more text"
Any tips?
In fish shell (and others), you want read
:
echo 'some text' | read varname
Following up on @ridiculous_fish's answer, use a while loop to consume all input:
function stdin2var
set -l a
while read line
set a $a $line
end
# $a is a *list*, so use printf to output it exactly.
echo (count $a)
printf "%s\n" $a
end
So you get
$ echo foo bar | stdin2var
1
foo bar
$ seq 10 | stdin2var
10
1
2
3
4
5
6
7
8
9
10
If you want to store stdin into a scalar variable:
function stdin2var
read -l -z a
set --show a
echo $a
end
echo some text\nsome more text | stdin2var
# $a: set in local scope, unexported, with 1 elements
# $a[1]: length=25 value=|some text\nsome more text\n|
# some text
# some more text
If you want to split lines in to a array:
function stdin2var
set -l a
IFS=\n read -az a
set --show a
for line in $a
echo $line
end
end
echo some text\nsome more text | stdin2var
# $a: set in local scope, unexported, with 2 elements
# $a[1]: length=9 value=|some text|
# $a[2]: length=14 value=|some more text|
# some text
# some more text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.