- Learning Linux Shell Scripting
- Ganesh Naik
- 361字
- 2021-06-25 22:02:55
Understanding variables
Let's learn about creating variables in a shell.
Declaring variables in Linux is very easy. We just need to use the variable name and initialize it with the required content.
$ person="Ganesh Naik"
To get the content of the variable, we need to add the prefix $ before the variable, for example:
$ echo person
person $ echo $person Ganesh Naik
The unset command can be used to delete the declared variable:
$ a=20$ echo $a$ unset a
The unset command will clear or remove the variable from the shell environment as well.
Here, the set command will show all variables declared in the shell:
$ person="Ganesh Naik"$ echo $person$ set
Here, using the declare command with the -x option will make it an environmental or global variable. We will find out more about environmental variables in the next section.
$ declare -x variable=value
Here, the env command will display all environmental variables:
$ env
Whenever we declare a variable, that variable will be available in the current Terminal or shell. This variable will not be available to any other Terminal or shell:
variable=value
Let's write a shell script, as follows:
#!/bin/bash # This script clears the window, greets the user, # and displays the current date and time. clear # Clear the window echo "SCRIPT BEGINS" echo "Hello $LOGNAME!" # Greet the user echo echo "Today's date and time:" date # Display current date and time echo # Will print empty line my_num=50 my_day="Sunday" echo "The value of my_num is $my_num" echo "The value of my_day is $my_day" echo echo "SCRIPT FINISHED!!" echo
Let's see the effect of $, "", '' on variable behavior:
#!/bin/bash planet="Earth" echo $planet echo "$planet" echo '$planet' echo $planet exit 0
The output is as follows:
Earth
Earth
$planet
$planet
From the preceding script's execution, we can observe that $variable and "$ variable" can be used to display the content of the variable. But if we use '$variable' or $variable, then the special functionality of the $ symbol is not available. The $ symbol is used as a simple text character instead of utilizing its special functionality of getting the variable's content.
- Dreamweaver 8中文版商業(yè)案例精粹
- Dreamweaver CS3網(wǎng)頁設(shè)計與網(wǎng)站建設(shè)詳解
- Visual C# 2008開發(fā)技術(shù)實例詳解
- 構(gòu)建高性能Web站點
- 網(wǎng)絡(luò)脆弱性掃描產(chǎn)品原理及應(yīng)用
- Linux系統(tǒng)下C程序開發(fā)詳解
- INSTANT VMware vCloud Starter
- 大數(shù)據(jù)案例精析
- 21天學(xué)通Linux嵌入式開發(fā)
- Java求職寶典
- MySQL Management and Administration with Navicat
- 人工智能:重塑個人、商業(yè)與社會
- Photoshop CS6白金手冊
- Cloud Native Development Patterns and Best Practices
- Learn T-SQL Querying