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.
- #!/bin/bash
- # swap.sh Function to perform the swap of 2 variables contents
- # Copyright (C) 2010 Author: Ferran Eloi Gutiérrez Martos <ferraneloi at gmail dot com>
- #
- # Last Modified: 2010-15-10
- # Usage and comments: You can just source the file and use the function.
- #
- # This code is released AS-IS, under an GPL license. The GPL license can be
- # found at http://www.gnu.org/licenses/gpl.html and is included
- # for your convenience at the bottom of the swap function.
- ##
- swap () {
- local x=\$"$1" # Name of the variable of the 1st parameter
- local y=\$"$2" # Name of variable passed as 2nd parameter
- local valueofx=`eval "expr \"$x\" "` #contents of 1st variable
- local valueofy=`eval "expr \"$y\" "` #contents of 2nd variable
- eval "$1=\"$valueofy\""
- eval "$2=\"$valueofx\""
- }
- # This program is free software: you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation, either version 3 of the License, or
- # (at your option) any later version.
- # This program is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- # You should have received a copy of the GNU General Public License
- # along with this program. If not, see <http://www.gnu.org/licenses/>.
- # Main program to test the function
- #Example of use 1: Simple swaps
- a=3
- b=8
- c=12
- echo "Example 1: Simple swaps"
- echo "Initial var. values" "a="$a "b="$b "c="$c
- swap a b #we swap content of variables a and b
- echo "Perform Swap (a,b) " "a="$a "b="$b "c="$c
- swap a c #now we swap a and c
- echo "Perform Swap (a,c) " "a="$a "b="$b "c="$c
- #Example of use 2: Sorting ascending elements
- a=12
- b=8
- c=5
- echo "Example 2: Simple sorting of 3 values"
- echo "Initial var. values" "a="$a "b="$b "c="$c
- if [ $a -gt $b ]
- then
- swap a b
- fi
- if [ $a -gt $c ]
- then
- swap a c
- fi
- if [ $b -gt $c ]
- then
- swap b c
- fi
- echo "Final Ascending sort:" "a="$a "b="$b "c="$c
Ya me diréis que tal
Share and Enjoy
Tinyurl for this post




Discussion (3) ¬
Fent una prova amb el Ferran!
provant