【shell】几个shell小功能

1 变量的使用

#!/bin/sh
#set varible a
a="hello world"
#print a
echo "A is:"
echo $a

输出:

A is: hello world

2 数字引用

#!/bin/sh
#set varible num
num=2
echo "this is the ${num}nd"

输出:

this is the 2nd

3 命令行参数使用示例

#!/bin/sh
echo "number of vars:"$#
echo "values of vars:"$*
echo "value of var1:"$1
echo "value of var2:"$2
echo "value of var3:"$3
echo "value of var4:"$4

运行

./s3 1 2 3 4

输出

number of vars:4 values of vars:1 2 3 4 value of var1:1 value of var2:2 value of var3:3 value of var4:4

4 函数调用

#!/bin/bash
hello="var1"
echo $hello
function func1 {
	local hello="var2"
	echo $hello
	}
func1
echo $hello

运行输出

var1 var2 var1

5 判断目录和文件

#!/bin/sh 
folder=/home 
[ -r "$folder" ] && echo "Can read $folder" 
[ -f "$folder" ] || echo "this is not file"

输出

Can read /home this is not file

6 循环

#!/bin/bash 
for day in Sun Mon Tue Wed Thu Fri Sat
do
	echo $day
done

运行输出

Sun Mon Tue Wed Thu Fri Sat

7 读取键盘按键事件

#!/bin/bash 
echo "Hit a key, then hit return."
read Keypress 
case "$Keypress" in
	[A-Z] ) echo "Uppercase letter";;
	[a-z] ) echo "Lowercase letter";;
	[0-9] ) echo "Digit";;
	* ) echo "Punctuation, whitespace, or other";;
esac

运行输出

8 字符串

#!/bin/bash 
for day in "Sun Mon Tue Wed Thu Fri Sat"
do
	echo $day
done

运行输出

Sun Mon Tue Wed Thu Fri Sat
经验分享 程序员 微信小程序 职场和发展