Create an integer variable

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

← Perform arithmetic operationsHomeCreate the constants variable →

declare -i y=10
echo "$y"

The '-i' option is used to make variable 'y' have the integer attribute. In other words, declare variable 'y' as the integer.

Examples

  • Create a shell script called intmath.sh:
#!/bin/bash
# set x,y and z to an integer data type
declare -i x=10
declare -i y=10
declare -i z=0
z=$(( x + y ))
echo "$x + $y = $z"

# try setting to character 'a'
x=a
z=$(( x + y ))
echo "$x + $y = $z"

Save and close the file. Run it as follows:

chmod +x intmath.sh
./intmath.sh

Sample outputs:

10 + 10 = 20
0 + 10 = 10
  • When you try to set the variable x to character 'a', shell converted it to an integer attribute i.e. zero number.

← Perform arithmetic operationsHomeCreate the constants variable →