Linux shell 示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux shell 示例相关的知识,希望对你有一定的参考价值。

一、环境
系统:Centos6.6 x64
shell:bash、sh

[[email protected] ~]$ hostname
Shell
[[email protected] ~]$ 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
[[email protected] ~]$ echo $SHELL
/bin/bash
[[email protected] ~]$ 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	World!"
echo -e "Hello	World!"
#printf使用文本或由空格分割的参数,可指定输出的宽度、对其方式等,可以格式化输出,默认情况下,printf不输出换行
printf "%-5s %-10s %-4s
" No. NAME Mark
printf "%-5s %-10s %-4s
" 1 Lee 80
printf "%-5s %-10s %-4.2f
" 2 Woon 90.456
printf "%-5s %-10s %-4.2f
" 3 James 85.654321
printf "%-5s %-10s %-5.3f
" 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 示例的主要内容,如果未能解决你的问题,请参考以下文章

代码片段:Shell脚本实现重复执行和多进程

linux下shell编程示例-获取进程id

Linux shell脚本示例

Linux shell 示例

linux-启动停止重启shell 简单shell示例

简单而有效的Linux Shell脚本示例(续一)