- Bash Cookbook
- Ron Brash Ganesh Naik
- 373字
- 2021-07-23 19:17:29
Hands-on variable assignment
Open a new blank file and add the following to it:
#!/bin/bash
PI=3.14
VAR_A=10
VAR_B=$VAR_A
VAR_C=${VAR_B}
echo "Let's print 3 variables:"
echo $VAR_A
echo $VAR_B
echo $VAR_C
echo "We know this will break:"
echo "0. The value of PI is $PIabc" # since PIabc is not declared, it will be empty string
echo "And these will work:"
echo "1. The value of PI is $PI"
echo "2. The value of PI is ${PI}"
echo "3. The value of PI is" $PI
echo "And we can make a new string"
STR_A="Bob"
STR_B="Jane"
echo "${STR_A} + ${STR_B} equals Bob + Jane"
STR_C=${STR_A}" + "${STR_B}
echo "${STR_C} is the same as Bob + Jane too!"
echo "${STR_C} + ${PI}"
exit 0
Notice the nomenclature. It is great to use a standardized mechanism to name variables, but to use STR_A and VAR_B is clearly not descriptive enough if used multiple times. In the future, we will use more descriptive names, such as VAL_PI to mean the value of PI or STR_BOBNAME to mean the string representing Bob's name. In Bash, capitalization is often used to describe variables, as it adds clarity.
Press Save and exit to a terminal (open one if one isn't already open). Execute your script after applying the appropriate permissions, and you should see the following output:
Lets print 3 variables:
10
10
10
We know this will break:
0. The value of PI is
And these will work:
1. The value of PI is 3.14
2. The value of PI is 3.14
3. The value of PI is 3.14
And we can make a new string
Bob + Jane equals Bob + Jane
Bob + Jane is the same as Bob + Jane too!
Bob + Jane + 3.14
First, we saw how we can use three variables, assign values to each of then, and print them. Secondly, we saw through a demonstration that the interpreter can break when concatenating strings (let's keep this in mind). Thirdly, we printed out our PI variable and concatenated it to a string using echo. Finally, we performed a few more types of concatenation, including a final version, which converts a numeric value and appends it to a string.
推薦閱讀
- INSTANT Mock Testing with PowerMock
- Learning ROS for Robotics Programming(Second Edition)
- Android開發(fā)精要
- 數(shù)據(jù)結(jié)構(Java語言描述)
- Java Web應用開發(fā)技術與案例教程(第2版)
- Bootstrap 4:Responsive Web Design
- SharePoint Development with the SharePoint Framework
- 區(qū)塊鏈架構之美:從比特幣、以太坊、超級賬本看區(qū)塊鏈架構設計
- Angular Design Patterns
- Mapping with ArcGIS Pro
- 一步一步學Spring Boot:微服務項目實戰(zhàn)(第2版)
- Mastering ASP.NET Web API
- 零基礎C語言學習筆記
- Unreal Engine Game Development Cookbook
- Learning Java Lambdas