Shell Script to swap values in two variables x and y

#!/bin/bash
# Shell Script to swap values in two variables x and y
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
echo "Enter value for x : "
read x
echo "Enter value for y : "
read y
echo "Before swap, x = $x and y = $y"
z=$x
x=$y
y=$z
echo "After swap, x = $x and y = $y"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • bhavu Oct 26, 2012 @ 13:31

    This may be a simpler of all!
    echo ENTER TWO VARIABLES
    read a b
    t=`expr $a`
    a=`expr $b`
    b=`expr $t`
    echo EXCHANGED VARIABLES ARE $a AND $b
    exit 0

  • Bash Guru Jul 31, 2012 @ 21:42

    a=5; b=3
    read a b <<<"$b $a"
    echo $a $b

    • newunx Dec 23, 2012 @ 6:08

      hi, can you plz explain what that “<<<" sign does…? "<<" is here document and what that thirs "<" sign does…? plz help..

      • Bash Guru Apr 18, 2013 @ 21:22

        < input a file
        << input a "here document"
        <<< input a "here string"

  • Anil Pappachan Apr 9, 2009 @ 6:03

    Try this option, we can avoid the third variable

    #!/bin/bash
    echo -e “Type the value of x : ”
    read x
    echo -e “Type the value of y : ”
    read y
    x=`expr $x + $y`
    y=`expr $x – $y`
    x=`expr $x – $y`

    echo -e “The value of x :$x ”
    echo -e “The value of y :$y “

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.