1. 程式人生 > >Linux shell 示例(一)

Linux shell 示例(一)

echo -e linu 定義變量 cheng lee export let linux amd

一、環境
系統:Centos6.6 x64
shell:bash、sh

[centos@Shell ~]$ hostname
Shell
[centos@Shell ~]$ lsb_release -a
LSB Version:    :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.6 (Final)
Release:    6.6
Codename:   Final
[centos@Shell ~]$ echo $SHELL
/bin/bash
[centos@Shell ~]$ ifconfig eth0 |grep "t addr"| awk -F ‘[: ]+‘ ‘{print $4}‘
192.168.101.110

二、腳本示例
1、終端打印

#!/bin/bash
#The printf of Linux termnal,Include "echo,printf"
#author by woon 
echo "The shell\`s name is $0"

#examples of echo,printf
#默認打印。輸出換行
echo "Hello World!" 
echo ‘Hello World!‘
#echo -n參數接受不換行輸出
echo -n "Hello World"
echo "Hello World"
#-e參數接受雙引號內字符串的轉移列表
echo "Hello\tWorld!"
echo -e "Hello\tWorld!"
#printf使用文本或由空格分割的參數,可指定輸出的寬度、對其方式等,可以格式化輸出,默認情況下,printf不輸出換行
printf "%-5s %-10s %-4s\n" No. NAME Mark
printf "%-5s %-10s %-4s\n" 1 Lee 80
printf "%-5s %-10s %-4.2f\n" 2 Woon 90.456
printf "%-5s %-10s %-4.2f\n" 3 James 85.654321
printf "%-5s %-10s %-5.3f\n" 4 Jeff 85.123789

運行結果:

The shell`s name is shell_print.sh
Hello World!
Hello World!
Hello WorldHello World
Hello   World!
-e Hello    World!
No.   NAME       Mark
1     Lee        80  
2     Woon       90.46
3     James      85.65
4     Jeff       85.124

2、環境變量

#!/bin/bash
#author by woon
#env#獲取全局環境變量
env > /tmp/env_$(date +%Y%m%d).$$
head -n 10 /tmp/env_$(date +%Y%m%d).$$
echo "^^^^^^^^^^^^^^^^^分隔符^^^^^^^^^^^^^^^^^^^^^^" 
#獲取單個全局變量的值
echo $PATH
echo "^^^^^^^^^^^^^^^^^分隔符^^^^^^^^^^^^^^^^^^^^^^"
#自定義變量和自定義全局變量,刪除環境變量
var="Hello World"
echo -n "$var" 
echo -n $var
echo ${var}
#設置全局環境變量
export VAR

#獲取當前的shell版本
echo $SHELL
#or
echo $0
#獲取變量的長度
var="Hello World"
echo ${#var}

#變量內容的刪除
path=$PATH
echo $path
echo "最短刪除,非貪婪模式,由前向後刪除"
var1=${path#/*:}
echo $var1
echo "貪婪模式,刪除匹配到最長的,由前向後刪除"
var2=${path##/*:}
echo $var2
echo "非貪婪模式%,由後向前刪除"
var3=${path%:*bin}
echo $var3

echo "貪婪模式,由後向前刪除最長的"
var4=${path%%:*bin}
echo $var4

3、shell數學運算

#!/bin/bash
#author by woon.
#數學運算
sum_jia=0
sum_cheng=1
i=1

while [ $i -le 10 ]; 
do
     let "sum_jia+=i"
     let "sum_cheng*=i"
     let "i += 2"
done
sum_jian1=$[ sum_cheng - sum_jia]
sum_jian2=$(( sum_cheng - sum_jia ))

echo $sum_jia
echo $sum_cheng
echo $sum_jian1
echo $sum_jian2

運行結果
$ ./shell_num.sh
25
945
920
920

Linux shell 示例(一)