linux 有关空格的知识点

有关空格的知识点

池塘春草梦

1.大括号{}

{ x=12;}  
#左边{ 后要有空格,右边;}前要有;

2.变量定义

​ 变量定义时=两边不能有空格

​ 定义字符串时,如果字符串包含空格,那么需要使用引号

age=28
#age =28  wrong
#age= 28  wrong
name="lala lalla"
name=lala lalla
#name=lala lalla  wrong

3.空格赋值

​ 空格赋值给变量的时候,需要用引号将空格括起来

p=' '
q= 
echo "la${p}la"
#la la
echo "la${q}la"
#lala

4.echo字符串时有" “和无” "时,输出空格的区别

read hi
hi           ih
echo $hi
#hi ih
echo "$hi"
#hi           ih

5.整型数被赋值为带空格的字符串时,系统将报错

declare -i k
k="kla klad"
#-bash: kla klad: syntax error in expression (error token is "klad")

6.expr表达式中的运算符两边都需要有空格,否则运算无法进行

expr 1 + 1
#2
expr 31 / 10
#3
i=1;expr $i + 1
#2
a=4;b=3
expr $a = $b
#0
expr $a != $b
#1
expr $a > $b
#1
expr $a < $b
#0

7.整型数关系运算时,[ ]的空格要求

[ 1 -gt 2 ]
echo $?
#1

8.字符串关系运算时,[ ]及=的空格要求

[ abc > bcd ]
echo $?
#1
[ -z akdlsfj ]
echo $?
#1
[ -n akjdfs ]
echo $?
#0
name=" Bee"
[ $name = Bee ]
echo $?
#0   不是我们想象的那样
[ "$name" = Bee ]
echo $?
#1   有空格的话要加""
a="  "
test -z $str
echo $?
#0
test -z "$str"
echo $?
#1    
#写脚本时徐特别注意,对字符串的判断尽可能都带上""

9.逻辑的与或非的[ ]中的空格

[ -r hello -a -w hello ]
[ ! -x hello ]

10.双中括号[[]]中的空格

[[ "abc" < "efg" && 1 -gt 2 ]]
echo $?
#1
[[ "abc" < "efg" || 1 -gt 2 ]]
echo $?
#0
name=" Bee"
[ $name = Bee ]
echo $?
#0
[ "$name" = Bee ]
echo $?
#1
[[ $name = Bee ]]
#1  用[[]]判断时字符串有空格,变量不加引号也可以得到正确的判断结果

11.双小括号(( ))中的空格

(( 3>1 || 3<1 ))
echo $?
#0   运算符两边不用空格(不过带了也不错)
x=1
(( $x==2 ))
echo $?
#1
(( $x==1 ))
echo $?
#0
(( !($x==1) ))
echo $?
#1
(( !($x!=1) ))
echo $?
#0

12.命令的与或非中的空格

[ -e a.txt ] && rm -f a.txt
#如果a.txt存在就删除它,不存在当然就不删除
cat absolute.sh
#!bin/bash
declare -i d
read d
(( $d>0 )) || d=-$d
echo $d
#显示一个数的绝对值

13.判断变量是否定义是的空格

[ -v PS1 ]
echo $?
#0
[ -v PSas1 ]
echo $?
#1
PSas1=1
[ -v PSas1 ]
echo $?
#0

14.if 语句中的空格

cat score_1.sh
#!/bin/bash
read score
if [ $score -ge 60 ]
#if 后要加一个空格 
#条件部分和上面所列一样
then
  echo Pass
else
  echo Not Pass
fi

cat score_2.sh
#!/bin/bash
read score
if (( $score >= 60 ))
#if 后带个空格
#条件判断和上述相同
then 
  echo Pass
else
  echo Not Pass
fi 

cat leap1.sh
#双中括号[[ ]]
#!/bin/bash
read -p "Input the year" year
if [[ $[$year % 400] -eq 0 ]]
#双中括号形式[[ ]]
then
  echo Leap
elif [[ $[$year % 4] -eq 0  &&  $[$year % 100] -ne 0 ]]  
#双中括号形式[[ ]]  
then 
  echo Leap
else
  echo Not Leap
fi

cat leap2.sh
#单中括号[ ]
#!/bin/bash
read -p "Input the year" year
if [ $[$year % 400] -eq 0 ]
then
  echo Leap
elif [ $[$year % 4] -eq 0  -a  $[$year % 100] -ne 0 ]
then
  echo Leap
else
  echo Not Leap
fi

cat leap_year_3.sh 
#双小括号(())
#!/bin/bash
read -p "Input the year" year
if (( $year%400==0 )) || (( $year%4==0 )) && (( $year%100!=0 ))
then
  echo Leap
else
  echo Not Leap
fi

15.case中的空格

cat case_vowel.sh
#!/bin/bash
read -p "input a-z" letter
case $letter in
  a|e|i|o|u)  echo "It's a vowel"
;;
  *) echo "Not a vowel"
esac
#这些其实不用空格缩进也可以

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>