We already have written a series of articles on Linux Shell Scripting which was warm welcomed that time and it was much relevant even now. Here is the link to the collection of articles on shell scripting.
Here in this article we will see the variables, its execution and its implementation in shell script.
Saving an Output
The output of a command can be redirected to standard output or a file and can be stored in a variable, as well. If the output of a command is large enough such that it does not fit the screen we are left only with the option of saving output to a file to in a variable. One advantage of saving output to variable is faster examination speed. Variables are saved into memory and hence it tends to be fast as compared to retrieval from file.
Variables in scripting Language
Variables are an important component used in Shell scripting and are declared using bash command “Declare”. To declare a variable say ‘level‘, we need to execute the below command.
$ declare LEVEL
Note: We need to use “typecast”, a built in statement for korn shell compatibility. The ‘declare’ is more advanced and contains all the features, hence is recommended when using BASH.
Rules
- A variable name must justify, the use of variable in the script.
- Using the same variable name throughout the program is strongly advised.
- Variables name can be uppercase as well as lowercase but by convention shell commands are in lowercase and hence we should use variables name in uppercase, so as to remove any confusion. e.g., TOTAL_BILLED_AMOUNT, SELL_REPORT, ORDER_RECEIPT, etc.
Implementation
A variable can be assigned a value using an equal sign (=). To assign an empty string to a variable we must not supply any value after equal sign.
$ LEVEL =
Check the value stored in variable ‘LEVEL’ as.
$ printf "%i" $LEVEL
printf, the command most of ‘C‘ programmers are aware of, prints data. %i – Represents Integer. We can replace it with %c for Character or %c for string, as and when required.
$LEVEL: Note the ‘$‘ which works as value substituter for the variable ‘LEVEL’.
Sample Output
$ printf "%i" $LEVEL 0
Assign a value to the variable.
$ LEVEL=0
Check the stored data in variable.
$ printf "%i" $LEVEL 0
NOTE: It is interesting to note that in both the cases, when we didn’t assigned the value to variable and when we assigned the value ‘0‘ to the variable ‘LEVEL‘ outputs 0. Although the output are same in both the cases but shell script handles both the variable declaration differently.
Assign a new value to the variable.
$ LEVEL=121
Check the stored data in variable.
$ printf "%i" $LEVEL 121
Unset a Variable
Declare is a BASH command and it creates variable only when executed. The variable so created remains in memory till the script stops or the variable is destroyed.
$ unset LEVEL
Predefined Variables in BASH
BASH has over 50 variables predefined. Some of these variables has a special meaning attached to BASH e.g., a variable RANDOM outputs a random number. If it is unset and then defined again, the original variable value is lost forever. Hence it is advised not to use any system defined variable.
Here is a list of some useful BASH variables.
- BASH—The full pathname of Bash.
- BASH_ENV—In a shell script, the name of the profile file executed before the script was started.
- BASH_VERSION—The version of Bash (for example, 2.04.0(1)-release).
- COLUMNS—The number of characters per line on your display (for example, 80).
- HOSTNAME—The name of the computer. Under some versions of Linux, this can be the machine name. On others, it can be a fully qualified domain name.
- HOSTTYPE—Type of computer.
- HOME—The name of your home directory.
- OSTYPE—The name of the operating system.
- PATH—Colon-separated list of search paths to find a command to execute.
- PPID—The process ID of the shell’s parent process.
- PROMPT_COMMAND—Command to execute before the setting of the PS1 primary prompt string.
- PWD—The current working directory (as set by the cd command).
- RANDOM—Returns a random number between 0 and 32767 each time it is referenced.
- SHELL—The preferred shell to use; for programs that start a shell for you.
- TERM—The terminal emulation type (for example, console).
The Rule of Word Splitting.
$ LEVEL=0 $ printf "%i" $LEVEL 0 AND $ LEVEL=”0” $ printf "%i" $LEVEL 0
In both the cases output remains same. So what’s the difference in result while using quotation?
Lets check the same with different variable data.
$ LEVEL=0 ; 1 ; 2 ; 3 ; 4 ; 5 bash: 1: command not found bash: 2: command not found bash: 3: command not found bash: 4: command not found bash: 5: command not found
$ printf "%i" $LEVEL 0
Not to mention, the output is not correct. BASH is taking the space after ‘0‘ as termination and hence the value of variable is set as ‘0‘. Now we try to use quotation for variables as below.
$ LEVEL=”0 ; 1 ; 2 ; 3 ; 4 ; 5” $ printf "%s" $LEVEL 0;1;2;3;4;5
Still the result is not correct. BASH took the variable values and removed all the spaces in between them. Hence printf didn’t interpreted 0,1,2,3,4,5 as distinct values. So what’s the solution?
printf "%s" "$LEVEL" 0 ; 1 ; 2 ; 3 ; 4 ; 5
Yeah! Putting the Variable substitution under quotes is the solution. Quotations groups characters in shell and interpret the special characters in a meaningful way.
Quotations can be used back-to-back and it is a good idea to enclose variable substitutions with quotes. Moreover it can be used to separate overall text from quotations. Here is an example.
$ LEVEL=5 $ FLAG_MESSAGE="I HAVE CLEARED LEVEL""$LEVEL"". I Deserve appreciation." $ printf “%s” “$FLAG_MESSAGE”
“I HAVE CLEARED LEVEL5. I Deserve appreciation.”
Separating chunks of quoted text with space will result into the same problem as discussed above. The bash will treat white space as termination. Another way of variable substitution is.
$ LEVEL=5 $ FLAG_MESSAGE="I HAVE CLEARED LEVEL ${LEVEL}. I Deserve appreciation." $ printf “%s” "$FLAG_MESSAGE" “I HAVE CLEARED LEVEL 5. I Deserve appreciation.”
Single quotes restricts BASH from printing Special characters.
$ printf “%s” '$FLAG_MESSAGE' “$FLAG_MESSAGE”
The Backslash (/)
Backslash works like single quote for one character. Have you thought how will you print (“)?
$ printf "%c" "\""
When %q grouped with printf, provides backslash after every word to ensure word spacing.
$ LEVEL=5 $ FLAG_MESSAGE="I HAVE CLEARED LEVEL ${LEVEL}. I Deserve appreciation." $ printf “%q” "$FLAG_MESSAGE" “I\ HAVE\ CLEARED\ LEVEL\ 5.\ I\ Deserve\ appreciation.”
That’s all for now. We always try to provide our readers with articles that are useful for them every now and then. The above covered article is vast hence rest of the topics with examples will be produced in the next article which will include ‘Attributes of variable’, ‘Variable exporting’ etc.
Till then Stay tuned and connected to Tecmint.com. Don’t forget to provide us with your valuable feedback in the comment section below.
Request to all,
I learned a lot from this website so thanks to all and I’m looking for a job in Linux in Mumbai if u have any leads and references so please let me know.
Hi Team,
Very good job from your side. It is very helpful for people like me(beginners).
Could you please share all the articles of Linux. i could find only till 11.
Thank you..