| 1 | #!/bin/bash |
| 2 | # badread.sh: |
| 3 | # Attempting to use 'echo and 'read' |
| 4 | #+ to assign variables non-interactively. |
| 5 | |
| 6 | # shopt -s lastpipe |
| 7 | |
| 8 | a=aaa |
| 9 | b=bbb |
| 10 | c=ccc |
| 11 | |
| 12 | echo "one two three" | read a b c |
| 13 | # Try to reassign a, b, and c. |
| 14 | |
| 15 | echo |
| 16 | echo "a = $a" # a = aaa |
| 17 | echo "b = $b" # b = bbb |
| 18 | echo "c = $c" # c = ccc |
| 19 | # Reassignment failed. |
| 20 | |
| 21 | ### However . . . |
| 22 | ## Uncommenting line 6: |
| 23 | # shopt -s lastpipe |
| 24 | ##+ fixes the problem! |
| 25 | ### This is a new feature in Bash, version 4.2. |
| 26 | |
| 27 | # ------------------------------ |
| 28 | |
| 29 | # Try the following alternative. |
| 30 | |
| 31 | var=`echo "one two three"` |
| 32 | set -- $var |
| 33 | a=$1; b=$2; c=$3 |
| 34 | |
| 35 | echo "-------" |
| 36 | echo "a = $a" # a = one |
| 37 | echo "b = $b" # b = two |
| 38 | echo "c = $c" # c = three |
| 39 | # Reassignment succeeded. |
| 40 | |
| 41 | # ------------------------------ |
| 42 | |
| 43 | # Note also that an echo to a 'read' works within a subshell. |
| 44 | # However, the value of the variable changes *only* within the subshell. |
| 45 | |
| 46 | a=aaa # Starting all over again. |
| 47 | b=bbb |
| 48 | c=ccc |
| 49 | |
| 50 | echo; echo |
| 51 | echo "one two three" | ( read a b c; |
| 52 | echo "Inside subshell: "; echo "a = $a"; echo "b = $b"; echo "c = $c" ) |
| 53 | # a = one |
| 54 | # b = two |
| 55 | # c = three |
| 56 | echo "-----------------" |
| 57 | echo "Outside subshell: " |
| 58 | echo "a = $a" # a = aaa |
| 59 | echo "b = $b" # b = bbb |
| 60 | echo "c = $c" # c = ccc |
| 61 | echo |
| 62 | |
| 63 | exit 0 |