当前位置:网站首页>Shell script - string

Shell script - string

2022-07-01 08:47:00 Little snail's way

character string (String) It is a combination of a series of characters . The string is Shell One of the most commonly used data types in programming ( Besides numbers and strings , There are no other types ).

Strings can be made of single quotes ' ' Surround , You can also use double quotes " " Surround , You can also use no quotes .

String example

str1=jack
str2="rose"
str3='100'

The difference between the three forms

  1. By single quotes ' ' Surrounded string :
  • Any character will be output as it is , Using variables in it is not valid .
  • Single quotation marks... Cannot appear in a string , Even if you escape single quotation marks .
  1. By double quotation marks " " Surrounded string :
  • If it contains a variable , Then the variable will be resolved ( Get the value of the variable ), Instead of outputting it as it is .
  • Double quotation marks can appear in the string , As long as it is escaped .
  1. A string that is not surrounded by quotation marks
  • Variables in strings that are not surrounded by quotation marks are also parsed , This point and double quotation marks " " The surrounding string is the same .
  • No spaces in the string , Otherwise, the string after the space will be parsed as other variables or commands .

Script

#!/bin/bash

name=jack
str1= My name is $name
str2=" There's a personal \" name \" It's called $name"
str3=' My friend's name is  $name'
echo $str1
echo $str2
echo $str3

Output :

 My name is jack
 There's a personal " name " It's called jack
 My friend's name is  $name

str1 It contains $name, It is resolved to a variable name References to .

str2 Contains quotation marks , But it was escaped ( By backslash \ The beginning indicates the escape character ).str2 It also includes $name, It is also resolved as a variable name References to .

str3 It also includes $name, But only as ordinary characters , Does not resolve to a variable name References to .

Get string length

The specific method is as follows ,${#string_name},string_name Represents the string name .
The code is as follows :

#!/bin/bash

name=jack
echo ${#name}

Output :

4
原网站

版权声明
本文为[Little snail's way]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010835460754.html