셸 스 크 립 트 변수 수치 계산

9904 단어 shell수치 계산
1. 산수 연산 자
산수 연산 을 실행 하면 각종 연산 기호 와 떨 어 질 수 없 으 며, 다른 프로 그래 밍 언어 와 마찬가지 로 셸 스 크 립 트 에 도 연산 기호 가 있다.일반적인 연산 기 호 는 다음 그림 과 같다.
위의 그림 에서 연산 기 호 는 흔히 볼 수 있 는 연산 명령 에 사 용 됩 니 다. 다음 그림 과 같이 연산 명령 을 자주 사용 합 니 다.
2. 쌍 소괄호 "()"연산 명령
2.1 쌍 소괄호 수치 연산 의 기초 문법
쌍 소괄호 '()' 의 역할 은 수치 연산 과 수 치 를 비교 하 는 것 으로 효율 이 높다.
2.2 쌍 소괄호 수치 연산 사례
사례 1: "()"를 이용 하여 간단 한 연산 을 한다.
[root@shellbiancheng ~]# echo $((2+4))
6
[root@shellbiancheng ~]# echo $((2+5))
7
[root@shellbiancheng ~]# echo $((2-5))
-3
[root@shellbiancheng ~]# ((i=4))
[root@shellbiancheng ~]# ((i=i*5))
[root@shellbiancheng ~]# echo $i
20

사례 2: "()"를 이용 하여 약간 복잡 한 총화 연산 을 한다.
[root@shellbiancheng ~]# ((a=1+2**4-4%3))
[root@shellbiancheng ~]# echo $a
16
[root@shellbiancheng ~]# b=$((1+2**4-4%3))
[root@shellbiancheng ~]# echo $b
16
[root@shellbiancheng ~]# echo $((1+2**4-4%3))
16
[root@shellbiancheng ~]# a=$((100*(100+1)/2)) 利用数学公式计算1到100的和
[root@shellbiancheng ~]# echo $a
5050
[root@shellbiancheng ~]# echo $((100*(100+1)/2))
5050

사례 3: '()' 쌍 괄호 로 비교 및 판단
[root@shellbiancheng ~]# echo $((1>2))
0
[root@shellbiancheng ~]# echo $((1<2)) 
1
[root@shellbiancheng ~]# echo $((1==1))
1
[root@shellbiancheng ~]# if ((1<2&&1==1))
> then
> echo yes
> fi
yes

알림: 두 개의 작은 괄호 "()"가 처리 하 는 연산 은 정수 (정형) 여야 하 며, 부동 소수점 (소수) 이나 문자열 이 어야 합 니 다.bc 명령 과 awk 명령 은 부동 소수점 (소수) 연산 에 사용 할 수 있 습 니 다.
사례 4: 변수 전후 사용 - + 특수 연산 자의 표현 식
a++表示先输出a的值在进行自增运算(即a++相当于a=a+1)
[root@shellbiancheng ~]# a=10
[root@shellbiancheng ~]# echo $((a++))
10
[root@shellbiancheng ~]# echo $a
11
 ++a表示先进行自增运算,在输出a的值
[root@shellbiancheng ~]# a=10
[root@shellbiancheng ~]# echo $((++a))
11
[root@shellbiancheng ~]# echo $a
11
a--表示先输出a的值,再进行递减运算
[root@shellbiancheng ~]# a=10
[root@shellbiancheng ~]# echo $((a--))
10
[root@shellbiancheng ~]# echo $a
9
 --a表示先进行递减预算再输出a的值
[root@shellbiancheng ~]# a=10
[root@shellbiancheng ~]# echo $((--a))
9
[root@shellbiancheng ~]# echo $a
9

사례 5: 각종 "()"이중 괄호 의 연산 셸 스 크 립 트 예제
[root@shellbiancheng jiaobenlianxi]# cat shuzhijisuan.sh
#!/bin/bash
a=$1
b=$2

if [ $# -eq 2  ];then

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"

else
echo $"Usage:Please enter two integers for example $0{2|1}"

fi

실행 결 과 는 다음 과 같 습 니 다.
[root@shellbiancheng jiaobenlianxi]# sh shuzhijisuan.sh 2 1
a+b=3
a-b=1
a*b=2
a/b=2
a**b=2
a%b=0

3. let 연산 명령
let 연산 명령 의 문법 형식 은 let 할당 식 입 니 다.
let 할당 식 의 기능 은 다음 과 같 습 니 다. (할당 식)
범례 1: 독립 변수 에 1 을 추가 합 니 다.
[root@shellbiancheng ~]# i=3
[root@shellbiancheng ~]# i=i+1  开头先不用let赋值
[root@shellbiancheng ~]# echo $i 输出时发现打印结果为i+1,没有计算
i+1
[root@shellbiancheng ~]# unset i
[root@shellbiancheng ~]# i=3
[root@shellbiancheng ~]# let i=i+1  采用let赋值在输出
[root@shellbiancheng ~]# echo $i
4

알림: let i = i + 1 은 (i = i + 1) 에 해당 하지만, 쌍 소괄호 의 방식 은 효율 이 높다.
범례 2: 웹 서비스 상 태 를 감시 하고 두 번 방문 하 는 데 실패 하면 경찰 에 신고 합 니 다.
[root@linzhongniao scripts]# cat checkurl_let.sh
#!/bin/bash
function CheckUrl(){
timeout=5
fails=0
success=0
while true
do
wget --timeout=$timeout --tries=1 ww.baidu.cm -q -O /dev/null
if [ $? -ne 0 ];then
let fails=fails+1

else
let success+=1
fi
if [ $success -ge 1 ];then
echo success
exit 0
fi
if [ $fails -ge 2 ];then
Critical="sys is down.."
echo $Critical|mail -s "$Critical" [email protected]
exit 2
fi
done
}
CheckUrl

4. expr 명령 의 용법
4.1 expr 명령 의 기본 용법 예시
expr (evaluate expressions 구직 표현 식) 명령 은 정수 연산 에 도 사용 할 수 있 고 문자열 길이, 일치 하 는 연산 처리 에 도 사용 할 수 있 습 니 다.
(1) expr 는 계산 에 사용
문법: expr Expression
범례 1: expr 연산 명령 용법
[root@linzhongniao ~]# expr 1+1
1+1
[root@linzhongniao ~]# expr 1 + 1
2
[root@linzhongniao ~]# expr 1 - 1
0
[root@linzhongniao ~]# expr 1 * 1
expr: syntax error
[root@linzhongniao ~]# expr 1 \* 1
1
[root@linzhongniao ~]# expr 1 / 1 
1

알림:
1. 연산 자 와 계산 에 사용 되 는 숫자 양 끝 에 빈 칸 이 있어 야 합 니 다. 그렇지 않 으 면 오류 가 발생 할 수 있 습 니 다.
2. 곱 하기 번 호 를 사용 할 때 는 반드시 반사 선 으로 의 미 를 바 꿔 야 한다.
(2) expr 배합 변수 계산
[root@linzhongniao ~]# i=2
[root@linzhongniao ~]# i=`expr $i + 1`
You have new mail in /var/spool/mail/root
[root@linzhongniao ~]# echo $i
3

4.2 expr 실전 사례
(1) 변수 나 문자열 이 정수 인지 아 닌 지 를 판단 하 는 방법
expr 를 이용 하여 변수 나 문자열 이 정수 여야 하 는 규칙 을 계산 할 수 있 습 니 다. 하나의 변수 나 문자열 과 이미 알 고 있 는 정수 (0 이 아 닌) 를 더 해서 명령 반환 값 이 0 인지, 0 이면 덧셈 을 하 는 변수 나 문자열 을 정수 로 생각 합 니 다. 그렇지 않 으 면 정수 가 아 닙 니 다.
범례 1: expr 를 통 해 변수 나 문자열 이 정수 인지 여 부 를 판단 합 니 다.
[root@shellbiancheng jiaobenlianxi]# i=4
[root@shellbiancheng jiaobenlianxi]# expr $i + 1 &>/dev/null
[root@shellbiancheng jiaobenlianxi]# echo $?
0
[root@shellbiancheng jiaobenlianxi]# i=asd
[root@shellbiancheng jiaobenlianxi]# expr $i + 1 &>/dev/null
[root@shellbiancheng jiaobenlianxi]# echo $?
2

범례 2: read 읽 기 방식 으로 입력 을 계속 기다 리 고 입력 한 값 이 정수 인지 판단 합 니 다.
[root@shellbiancheng jiaobenlianxi]# cat read_expr.sh
#!/bin/bash
while true
do
read -p "pls input:" a
expr $a + 0 >/dev/null 2>&1
[ $? -eq 0 ] && echo int || echo chars   
done

범례 3: 두 개의 작은 괄호 를 수정 한 사례 5. 입력 한 매개 변수의 개수 와 입력 한 매개 변수 가 정수 인지 판단 할 수 있 도록 요구한다.
[root@shellbiancheng jiaobenlianxi]# cat shuzhijisuan.sh 
#!/bin/bash
a=$1
b=$2
expr $a + $b + 1 >/dev/null 2>&1
if [ $? -eq 0 -a $# -eq 2  ];then

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"

else
echo $"Usage:Please enter two integers for example num1 num2"

fi

(2) expr 는 파일 확장자 가 요구 에 부합 되 는 지 판단 합 니 다.
범례 1: expr 를 통 해 파일 확장자 가 요구 에 부합 되 는 지 판단 합 니 다.
[root@shellbiancheng jiaobenlianxi]# cat expr1.sh
#!/bin/bash

if expr "$1" : ".*\.txt" &>/dev/null

then
echo "you are using $1"
else
echo "pls use *.txt file"
fi

(3) expr 를 통 해 문자열 의 길 이 를 계산한다.
[root@shellbiancheng ~]# char="I am linzhongniao"
[root@shellbiancheng ~]# expr length "$char"
17
[root@shellbiancheng ~]# echo ${#char}
17
[root@shellbiancheng ~]# echo ${char}|wc -L
17
[root@shellbiancheng ~]# echo ${char}|awk '{print length($0)}'
17

5. bc 명령 용법
bc 는 UNIX/Linux 의 계산기 이기 때문에 계산기 외 에 명령 행 계산 도구 로 도 사용 할 수 있다.
범례 1: bc 명령 계산기 사용
[root@shellbiancheng ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
1+1
2

범례 2: bc 를 명령 행 에 사용 하여 계산 기능 을 실현 합 니 다.
[root@shellbiancheng ~]# echo 1+1|bc
2
[root@shellbiancheng ~]# echo 1.1+1|bc 
 2.1
[root@shellbiancheng ~]# echo 6.2-1.1|bc
 5.1
[root@shellbiancheng ~]# echo "scale=6;355/113"|bc 使用scale保留六位小数
 3.141592
[root@shellbiancheng ~]# echo "scale=7;355/113"|bc
 3.1415929
[root@shellbiancheng ~]# i=2
[root@shellbiancheng ~]# i=`echo $i+6|bc`
[root@shellbiancheng ~]# echo $i
8

알림: 정수 연산 은 "()", let, expr 등 을 사용 할 수 있 으 며, 소수 라면 bc 또는 awk 를 사용 할 수 있 으 며, awk 를 사용 하 는 것 을 추천 합 니 다.
6. awk 계산
awk 계산 은 소수 와 정 수 를 사용 합 니 다. 특히 명령 행 계산, 특히 소수 가 정확 합 니 다. 예 는 다음 과 같 습 니 다.
[root@shellbiancheng ~]# echo "2.3 4.5"|awk '{print ($1-$2)}'
 -2.2  $1为第一个数字,$2为第二个数字用空格分开
[root@shellbiancheng ~]# echo "2.3 4.5"|awk '{print ($1+$2)}'
 6.8
[root@shellbiancheng ~]# echo "2.3 4.5"|awk '{print ($1*$2)}'
 10.35
[root@shellbiancheng ~]# echo "2.3 4.5"|awk '{print ($1/$2)}'
 0.511111
[root@shellbiancheng ~]# echo "2.3 4.5"|awk '{print ($1+1)/$2}'
 0.733333

7. declare 명령 의 용법
[root@shellbiancheng ~]# declare -i a=16 b=7 -i参数可以将变量定义为×××
[root@shellbiancheng ~]# a=a+b
[root@shellbiancheng ~]# echo $a
23

8. $[] 기호의 연산 예시
[root@shellbiancheng ~]# i=2
[root@shellbiancheng ~]# i=$[i+2]
[root@shellbiancheng ~]# echo $i
4
[root@shellbiancheng ~]# echo $[2+2]
4
[root@shellbiancheng ~]# echo $[2*2]
4
[root@shellbiancheng ~]# echo $[2/2]
1
[root@shellbiancheng ~]# declare  A=3 B=7  
[root@shellbiancheng ~]# declare C=`expr $A + $B`
[root@shellbiancheng ~]# echo $C 
10

9. 기본 셸 변 수 는 read 명령 의 연산 실전 을 입력 합 니 다.
9.1 read 명령 기초
셸 변 수 는 직접 할당 과 스 크 립 트 전송 을 제외 하고 read 명령 을 사용 하여 표준 입력 에서 얻 을 수 있 습 니 다.read 는 내 장 된 명령 으로 help read 를 통 해 도움말 을 볼 수 있 습 니 다.
문법 형식:
read [매개 변수] [변수 명]
상용 매개 변 수 는 다음 과 같 습 니 다.
- p (prompt): 알림 정보 설정
- t (timeout): 입력 대기 시간 을 설정 합 니 다. 단 위 는 기본 초 입 니 다.
범례 1: read 기본 읽 기 기능 실현
[root@shellbiancheng ~]# read -p "pls input one number:" num
pls input one number:1
[root@shellbiancheng ~]# echo $num
1
[root@shellbiancheng ~]# read -p "pls input two number:" num1 num2
pls input two number:1 2
[root@shellbiancheng ~]# echo $num1
1
[root@shellbiancheng ~]# echo $num2
2

알림: read 읽 기 는 사용자 의 입력 을 대화 식 으로 받 은 다음 변수 에 값 을 부여 합 니 다.
범례 2: '()' 쌍 괄호 변수 계산 에서 의 사례 5 를 read 읽 기 방식 으로 변경 합 니 다.
[root@shellbiancheng jiaobenlianxi]# cat shuzhijisuan.sh   
#!/bin/bash
read -p "pls input two number:" a b
expr $a + $b + 1 >/dev/null 2>&1
if [ $? -eq 0 ];then

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"

else
echo $"Usage:Please enter two integers for example num1 num2"

fi

좋은 웹페이지 즐겨찾기