官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 临安市| 嘉黎县| 安康市| 公主岭市| 德令哈市| 普兰店市| 汶上县| 凤冈县| 读书| 馆陶县| 无极县| 普陀区| 姜堰市| 齐齐哈尔市| 清新县| 绵阳市| 嘉禾县| 大冶市| 常州市| 凤翔县| 三穗县| 象州县| 龙岩市| 岱山县| 淄博市| 华宁县| 兴国县| 波密县| 隆林| 宝鸡市| 扬中市| 青铜峡市| 全州县| 镶黄旗| 秦皇岛市| 洮南市| 菏泽市| 九龙坡区| 咸宁市| 庆安县| 南涧|