- 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.
推薦閱讀
- Git Version Control Cookbook
- C語言程序設計習題解析與上機指導(第4版)
- Vue.js 3.0源碼解析(微課視頻版)
- Animate CC二維動畫設計與制作(微課版)
- Hadoop+Spark大數據分析實戰
- 零基礎Java學習筆記
- JBoss:Developer's Guide
- Zabbix Performance Tuning
- Emotional Intelligence for IT Professionals
- 零基礎輕松學C++:青少年趣味編程(全彩版)
- JavaScript悟道
- Koa與Node.js開發實戰
- Managing Windows Servers with Chef
- Internet of Things with Arduino Cookbook
- Selenium WebDriver自動化測試完全指南