Shell编程(四)Shell变量

时间:2023-03-08 21:35:50

1. 自定义变量(仅在当前shell生效)

1.1 定义变量

#!/usr/bin/bash
ip=115.239.210.27 if ping -c1 $ip &>/dev/null ;then # &>/dev/null: output of ping $ip is null
echo "$ip is up."
else
echo "$ip is down."
fi

Shell编程(四)Shell变量

1.2 输入变量

#!/usr/bin/bash
read ip ping -c1 $ip &>/dev/null
if [ $? -eq ]; then
echo "$ip is up."
else
echo "$ip is down."
fi

Shell编程(四)Shell变量

1.3 位置变量 ($, $, $...${}....)

#!/bin/bash

ping -c1 $1 &>/dev/null
if [ $? -eq 0 ]; then
echo "$1 is up."
else
echo "$1 is down."
fi

Shell编程(四)Shell变量

1.4 预定义变量 ( $ \$0, \$*, \$@, \$\#, \$\$, \$!, \$? $ )

Shell编程(四)Shell变量

#!/bin/bash
echo "the par of 2: $2"
echo "the par of 1: $1"
echo "the par of 4: $4" echo "all par: $*"
echo "all par: $@"
echo "the num of par: $#"
echo "the PID of cur process: $$" echo '$1='$
echo '$2='$
echo '$3='$
echo '$*='$*
echo '$@='$@
echo '$#='$#
echo '$$='$$

Shell编程(四)Shell变量

Shell编程(四)Shell变量

1.5 综合

#!/bin/bash
# if user have no parma
if [ $# -eq ]; then
echo "usage: `basename $0` file"
fi if [ ! -f $ ]; then # not a file
echo "erro file!"
fi echo "ping........." for ip in `cat $`
do
ping -c1 $ip &>/dev/null
if [ $? -eq ];then
echo "$ip is up."
else
echo "$ip is down."
fi
done

Shell编程(四)Shell变量

2. 环境变量(在当前shell和子shell有效)

2.1 export

echo "ip1 is $ip1"
echo "ip2 is $ip2"

Shell编程(四)Shell变量

Shell编程(四)Shell变量(ip2 是环境变量)

2.2  在一个bash文件中调用其他bash文件

Shell编程(四)Shell变量

2.3 env 查看所有环境变量

3. 命令代换: ` `或 $()

Shell编程(四)Shell变量

#! /bin/bash

pwd
ls DATA=$(date) echo $DATA $(curl www.itcast.cn > .html) pwd

Shell编程(四)Shell变量

4. 算术代换

4.1 $(()), expr

4.2 $[], let

Shell编程(四)Shell变量

5. 小数计算

echo "scale=3;6/4" |bc

Shell编程(四)Shell变量

awk 'BEGIN{print 1/2}'

Shell编程(四)Shell变量

6. 变量"内容"的删除和替换

Shell编程(四)Shell变量

6.1 从前往后删除(#:最近匹配; ##:贪婪匹配)

Shell编程(四)Shell变量

6.2 从后往前删除(%:最近匹配; %%:贪婪匹配)

Shell编程(四)Shell变量

Shell编程(四)Shell变量

6.3 索引方式切片

Shell编程(四)Shell变量

6.4 替换

Shell编程(四)Shell变量

贪婪匹配

Shell编程(四)Shell变量

6.6 替代 ${变量名-新的变量值}

变量没有被赋值:会使用“新的变量值”替代

变量有被赋值(包括空值):不会被替代

6.61 - 和 :-

Shell编程(四)Shell变量

6.62 + 和 :+

Shell编程(四)Shell变量

6.63 = 和 :=

Shell编程(四)Shell变量

6.64 ? 和 :?

Shell编程(四)Shell变量