<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> <META NAME="GENERATOR" CONTENT="SGML-Tools 1.0.9"> <TITLE>BASH Programming - Introduction HOW-TO: Variables</TITLE> <LINK HREF="Bash-Prog-Intro-HOWTO-6.html" REL=next> <LINK HREF="Bash-Prog-Intro-HOWTO-4.html" REL=previous> <LINK HREF="Bash-Prog-Intro-HOWTO.html#toc5" REL=contents> </HEAD> <BODY> <A HREF="Bash-Prog-Intro-HOWTO-6.html">Next</A> <A HREF="Bash-Prog-Intro-HOWTO-4.html">Previous</A> <A HREF="Bash-Prog-Intro-HOWTO.html#toc5">Contents</A> <HR> <H2><A NAME="s5">5. Variables</A> </H2> <P> You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. <P> You have no need to declare a variable, just assigning a value to its reference will create it. <P> <P> <P> <H2><A NAME="ss5.1">5.1 Sample: Hello World! using variables</A> </H2> <P> <BLOCKQUOTE><CODE> <PRE> #!/bin/bash STR="Hello World!" echo $STR </PRE> </CODE></BLOCKQUOTE> <P> <P> Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then the VALUE of this variable is retrieved by putting the '$' in at the beginning. Please notice (try it!) that if you don't use the '$' sign, the output of the program will be different, and probably not what you want it to be. <H2><A NAME="ss5.2">5.2 Sample: A very simple backup script (little bit better)</A> </H2> <P> <BLOCKQUOTE><CODE> <PRE> #!/bin/bash OF=/var/my-backup-$(date +%Y%m%d).tgz tar -cZf $OF /home/me/ </PRE> </CODE></BLOCKQUOTE> <P> This script introduces another thing. First of all, you should be familiarized with the variable creation and assignation on line 2. Notice the expression '$(date +%Y%m%d)'. If you run the script you'll notice that it runs the command inside the parenthesis, capturing its output. <P> <P> Notice that in this script, the output filename will be different every day, due to the format switch to the date command(+%Y%m%d). You can change this by specifying a different format. <P> Some more examples: <P> echo ls <P> echo $(ls) <H2><A NAME="ss5.3">5.3 Local variables</A> </H2> <P> Local variables can be created by using the keyword <I>local</I>. <P> <BLOCKQUOTE><CODE> <PRE> #!/bin/bash HELLO=Hello function hello { local HELLO=World echo $HELLO } echo $HELLO hello echo $HELLO </PRE> </CODE></BLOCKQUOTE> <P> This example should be enought to show how to use a local variable. <HR> <A HREF="Bash-Prog-Intro-HOWTO-6.html">Next</A> <A HREF="Bash-Prog-Intro-HOWTO-4.html">Previous</A> <A HREF="Bash-Prog-Intro-HOWTO.html#toc5">Contents</A> </BODY> </HTML>