Page 1 of 1

Bash Scripting - Using Variables how to use variables in bash scripts Rate Topic: -----

#1 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 387
  • View blog
  • Posts: 1,663
  • Joined: 16-May 09

Post icon  Posted 24 November 2009 - 12:11 PM

In previous part of the tutorial, we learned how to write a very simple script to execute system commands (I used tar for example) and print different messages on the screen. In this part we are going to learn how to use variables in our scripts.

Using Variables
Defining variables in a bash script is so simple! you don't have to worry about the datatype as you do in languages like C/C++. Just go on and define the variable like the following:
#Define a string variable, don't forget the quotes!!
#if your variable is not string, omit the quotes
STR="A Simple String Here"
echo $STR
OK, don't panic about the $ sign in the echo line, here's why: When you want to use a variable's value, you have to add the $ at it's beginning. If you have worked with PHP before, you probably already know this.

Here's another example:
#define a string - it holds a directory location
#another for a file
cp $LOC$FIL ./backup-test.jpg
In the above example, we combined both strings and used them both in a cp command.

Another note on the variables, you can use a program's outputs on-the-fly for another's input like this:
echo $(grep "kian" ~kian/names.txt)
What this line does is: catch the output of the grep command and use it like a variable - just like our previous examples but this time we don't have a variable name... so it cannot be used in other lines of the script.
Now you should have learned the basic usage of variables in your scripts, in the next part we are going to learn about if statements and a little script to know if user has root privileges or not. :)

Is This A Good Question/Topic? 0
  • +

Page 1 of 1