Bash · 1821 bytes Raw Blame History
1 #!/bin/sh
2 TEST_PREFIX="[read]"
3 . "$(cd "$(dirname "$0")" && pwd)/test_harness.sh"
4
5 section "1. read basic"
6 compare_output "read from herestring" 'read VAR <<< "hello"; echo $VAR'
7 compare_output "read multiple vars" 'read A B C <<< "one two three"; echo "$A|$B|$C"'
8 compare_output "read excess into last var" 'read A B <<< "one two three four"; echo "$A|$B"'
9 compare_output "read single var gets all" 'read LINE <<< "hello world test"; echo "$LINE"'
10 compare_output "read with empty input" 'read VAR <<< ""; echo ">${VAR}<"'
11
12 section "2. read flags"
13 compare_output "read -r preserves backslash" 'read -r VAR <<< "hello\\world"; echo "$VAR"'
14 compare_output "read without -r interprets backslash" 'read VAR <<< "hello\\\\world"; echo "$VAR"'
15 compare_output "read -a into array" 'read -a ARR <<< "a b c"; echo ${ARR[0]} ${ARR[1]} ${ARR[2]}'
16 compare_output "read -a array length" 'read -a ARR <<< "x y z"; echo ${#ARR[@]}'
17
18 section "3. read with IFS"
19 compare_output "read with colon IFS" 'IFS=: read A B C <<< "x:y:z"; echo "$A|$B|$C"'
20 compare_output "read with comma IFS" 'IFS=, read A B C <<< "a,b,c"; echo "$A|$B|$C"'
21 compare_output "read with custom IFS excess" 'IFS=: read A B <<< "x:y:z"; echo "$A|$B"'
22 compare_output "read with space IFS default" 'read A B <<< " hello world "; echo ">$A<>$B<"'
23
24 section "4. read from heredoc"
25 compare_output "read from heredoc" 'read VAR << EOF
26 hello
27 EOF
28 echo $VAR'
29 compare_output "read loop from heredoc" 'while read line; do echo "got:$line"; done << EOF
30 alpha
31 beta
32 EOF'
33
34 section "5. read edge cases"
35 compare_exit "read with no input returns 1" 'echo -n "" | read VAR'
36 compare_output "read preserves whitespace with IFS empty" 'IFS= read line <<< " spaces "; echo ">$line<"'
37 compare_output "read -r with trailing backslash" 'read -r VAR <<< "end\\"; echo "$VAR"'
38
39 print_summary