Hola a todos, os presento una función que he creado para hacer un swap o intercambio de variables en  bash al estilo clásico de programación. Espero que pueda servir a futuros programadores, por eso la libero el código con licencia GPL de opensource.

swap.sh   
  1. #!/bin/bash
  2. # swap.sh   Function to perform the swap of 2 variables contents
  3. # Copyright (C) 2010  Author: Ferran Eloi Gutiérrez Martos <ferraneloi at gmail dot com>
  4. #
  5. # Last Modified: 2010-15-10
  6. # Usage and comments: You can just source the file and use the function.
  7. #
  8. # This code is released AS-IS, under an GPL license. The GPL license can be
  9. # found at http://www.gnu.org/licenses/gpl.html and is included
  10. # for your convenience at the bottom of the swap function.
  11. ##
  12. swap () {
  13. local x=\$"$1"   # Name of the variable of the 1st parameter
  14. local y=\$"$2"   # Name of variable passed as 2nd parameter
  15. local valueofx=`eval "expr \"$x\" "`  #contents of 1st variable
  16. local valueofy=`eval "expr \"$y\" "`  #contents of 2nd variable
  17. eval "$1=\"$valueofy\""
  18. eval "$2=\"$valueofx\""
  19. }
  20. #    This program is free software: you can redistribute it and/or modify
  21. #    it under the terms of the GNU General Public License as published by
  22. #    the Free Software Foundation, either version 3 of the License, or
  23. #    (at your option) any later version.
  24. #    This program is distributed in the hope that it will be useful,
  25. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  27. #    GNU General Public License for more details.
  28. #    You should have received a copy of the GNU General Public License
  29. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  30. # Main program to test the function
  31. #Example of use 1: Simple swaps
  32. a=3
  33. b=8
  34. c=12
  35. echo "Example 1: Simple swaps"
  36. echo "Initial var. values" "a="$a "b="$b "c="$c
  37. swap a b  #we swap content of variables a and b
  38. echo "Perform Swap (a,b) " "a="$a "b="$b "c="$c
  39. swap a c  #now we swap  a and c
  40. echo "Perform Swap (a,c) " "a="$a "b="$b "c="$c
  41. #Example of use 2:  Sorting ascending elements
  42. a=12
  43. b=8
  44. c=5
  45. echo "Example 2: Simple sorting of 3 values"
  46. echo "Initial var. values" "a="$a "b="$b "c="$c
  47. if [ $a -gt $b ]
  48. then
  49. swap a b
  50. fi
  51. if [ $a -gt $c ]
  52. then
  53. swap a c
  54. fi
  55. if [ $b -gt $c ]
  56. then
  57. swap b c
  58. fi
  59. echo "Final Ascending sort:" "a="$a "b="$b "c="$c

Ya me diréis que tal ;-)

VN:F [1.9.22_1171]
Rating: 10.0/10 (3 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 3 votes)
Función bash swap, 10.0 out of 10 based on 3 ratings
Share and Enjoy
Tinyurl for this post