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

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

主站蜘蛛池模板: 大兴区| 大方县| 浙江省| 大同市| 方城县| 青神县| 米林县| 乡宁县| 荥经县| 潼关县| 霍林郭勒市| 屯门区| 旅游| 兴文县| 长顺县| 醴陵市| 福安市| 南投市| 厦门市| 陵川县| 平远县| 宕昌县| 新余市| 阳山县| 龙江县| 铜川市| 璧山县| 辉县市| 黄冈市| 静安区| 卓资县| 兴海县| 东平县| 沈丘县| 铅山县| 抚远县| 保靖县| 炎陵县| 五河县| 卫辉市| 昌江|