| 1 | #!/bin/bash |
| 2 | # revposparams.sh: Reverse positional parameters. |
| 3 | # Script by Dan Jacobson, with stylistic revisions by document author. |
| 4 | |
| 5 | |
| 6 | set a\ b c d\ e; |
| 7 | # ^ ^ Spaces escaped |
| 8 | # ^ ^ Spaces not escaped |
| 9 | OIFS=$IFS; IFS=:; |
| 10 | # ^ Saving old IFS and setting new one. |
| 11 | |
| 12 | echo |
| 13 | |
| 14 | until [ $# -eq 0 ] |
| 15 | do # Step through positional parameters. |
| 16 | echo "### k0 = "$k"" # Before |
| 17 | k=$1:$k; # Append each pos param to loop variable. |
| 18 | # ^ |
| 19 | echo "### k = "$k"" # After |
| 20 | echo |
| 21 | shift; |
| 22 | done |
| 23 | |
| 24 | set $k # Set new positional parameters. |
| 25 | echo - |
| 26 | echo $# # Count of positional parameters. |
| 27 | echo - |
| 28 | echo |
| 29 | |
| 30 | for i # Omitting the "in list" sets the variable -- i -- |
| 31 | #+ to the positional parameters. |
| 32 | do |
| 33 | echo $i # Display new positional parameters. |
| 34 | done |
| 35 | |
| 36 | IFS=$OIFS # Restore IFS. |
| 37 | |
| 38 | # Question: |
| 39 | # Is it necessary to set an new IFS, internal field separator, |
| 40 | #+ in order for this script to work properly? |
| 41 | # What happens if you don't? Try it. |
| 42 | # And, why use the new IFS -- a colon -- in line 17, |
| 43 | #+ to append to the loop variable? |
| 44 | # What is the purpose of this? |
| 45 | |
| 46 | exit 0 |
| 47 | |
| 48 | $ ./revposparams.sh |
| 49 | |
| 50 | ### k0 = |
| 51 | ### k = a b |
| 52 | |
| 53 | ### k0 = a b |
| 54 | ### k = c a b |
| 55 | |
| 56 | ### k0 = c a b |
| 57 | ### k = d e c a b |
| 58 | |
| 59 | - |
| 60 | 3 |
| 61 | - |
| 62 | |
| 63 | d e |
| 64 | c |
| 65 | a b |