5/26/2013

Linux: User defined variables? Place result of command into variable? Retrieve variable value?

Linux shell scripting uses variables in a somewhat different way than most common programming languages.

You first pick a name for your new variable -- ex. myValue

Then assign the value using the equal sign, with the variable name on the left, expression to be evaluated on the right (no extra spaces):
ex.
myValue=5000;
myValue=blue;
myValue="Snow White";
Complex strings must be put inside quotation marks.
To retrieve the value of your variable, add a dollar sign ($) in front of the variable name.
echo $myValue;
In the above examples, the output for each would be
5000
blue
Snow White
If you wanted to place  the result of a command into  a variable, you put the expression inside of parentheses and place a dollar sign in front of the opening paren:
myLineCount=$(wc -l myTargetFilename.txt);
echo "Number of lines: $myLineCount";
Output would be:
Number of lines: 250 myTargetFilename.txt

No comments :

Post a Comment