0
点赞
收藏
分享

微信扫一扫

Linux Bash Shell结构化命令

f12b11374cba 2022-03-11 阅读 45
linuxbash

结构化命令

if-then语句

	if command
	then
		command
	fi

不同于其他编程语言在if之后的对象是一个等式,这个等式结果为TRUE或FALSE,bash shell的if语句会运行if后面的命令,如果该命令退出状态码为0,则运行then如果不为0则then后不执行

例:

#!/bin/bash
#testing the if statement
if pwd
then
	echo "It worked"
fi

例:

#!/bin/bash
#testing a bad command
if IamNotaCommand
then
	echo "It worked"
fi
echo "We are outside the if statement"

例:

#!/bin/bash
#testing multiple commands in the then section
testuser=keynes
if grep $testuser /etc/passwd
then
	echo "This is my first command"
	echo "This is my second command"
	echo "I can even put in other commands besides echo"
	ls -a /home/$testuser/.b*
fi

设置一个不存在的账户

例:

#!/bin/bash
#testing multiple commands in the then section
testuser=NoSuchUser
if grep $testuser /etc/passwd
then
	echo "This is my first command"
	echo "This is my second command"
	echo "I can even put in other commands besides echo"
	ls -a /home/$testuser/.b*
fi

if-then-else语句

  if command
	then
	   commands
	else
	   commands
	fi

例:

#!/bin/bash
#testing the els section
testuser=NoSuchUser
if grep $testuser /etc/passwd
then
	echo "The bash fiels for user $testuser are:"
	ls -a /home/$testuser/.b*
	echo
else
	echo "The user $testuser does not exist on this system."
	echo
fi

嵌套if

例:

#!/bin/bash
#Testing nested ifs
testuser=NoSuchUser
if grep $testuser /etc/passwd
then 
	echo "The user $testuser exists on this system"
else
	echo "The user $testuser does not exist on this system"
	if ls -d /home/$testuser/
	then
		echo "However,$testuser has a directory"
fi

test命令

test命令提供了if-then语句测试,如果test命令中列出条件成立,test命令便退出并返回状态码0,否则返回非零状态码,使得if-then语句不会再被执行

例:

if test condition
then
	commands
fi

	bash shell 提供了另一种条件测试方法,无需声明test,
if [ condition ]
then
	commands
fi

例:

#!/bin/bash
#Testing the test command
if test
then
	echo "No expression returns a True"
else
	echo "No expression returns a False"
fi

例:

#!/bin/bash
#Testing the test command
my_variable="Full"
if test $my_variable
then
    echo "The $my_variable expression returns a True"
else
    echo "The $my_variable expression returns a False"
fi

例:

#!/bin/bash
#Testing the test command
my_variable=""
if test $my_variable
then
    echo "The $my_variable expression returns a True"
else
    echo "The $mys_variable expression returns a False"
fi

test命令的数值比较功能

数值比较

比较描述
n1 -eq n2检查n1是否与n2相等
n1 -ge n2检查n1是否大于或等于n2
n1 -gt n2检查n1是否大于n2
n1 -le n2检查n1是否小于等于n2
n1 -lt n2检查n1是否小于n2
n1 -ne n2检查n1是否不等于n2

例:

#!/bin/bash
#Using numeric test evaluations
value1=10
value2=11
if [ $value1 -gt 5 ]
then
    echo "The test value $value1 is greater than 5"
fi
if [ $value1 -eq $value2 ]
then
    echo "The values are equal"
else
    echo "The values are different"
fi
注:变量只可以存储浮点值

字符串比较

比较描述
str1 = str2检查str1是否和str2相同
str1 !=str2检查str1是否和str2不同
str1 < str2检查str1是否比str2小
str1 > str2检查str1是否比str2大
-n str1检查str1的长度是否非零
-z str1检查str1的长度是否为0

字符串相等性

例:

#!/bin/bash
# testing string equality
testuser=keynes
if [ $USER=$testuser ]
then
    echo "Welcome $testuser"
fi

例:

#!/bin/bash
# testing string equality
testuser=baduser
if [ $USER !=$testuser ]
then
    echo "This is not $testuser"
else
    echo "Welcome $testuser"
fi

字符串顺序

例:

#!/bin/bash
#mis-using string comparisons
val1=baseball
val2=hockey
if [ $var1 \>$val2 ]
then
	echo "$val1 is greater then $val2"
else
	echo "$varl1 is less then $val2"
fi

字符串大小

-n 判断变量字符串长度非0

-z 判断变量字符串长度为0

例:

#!/bin/bash
#testing string length
val1=testing
val2=''
if [ -n $val1 ]
then
	echo "The string '$val1' is not empty"
else
	echo "The string '$val1' is empty"
fi
if [ -z $val2 ]
then
	echo "The string '$val2' is empty"
else
	echo "The string '$val2' is not empty"
fi
if [ -z $val3 ]
then
	echo "The string '$var3' is empty"
else
	echo "The string '$var3' is not empty"
fi

文件比较

比较描述
-d file检查file是否存在且是个目录
-e file检查file是否存在
-f file检查file是否存在且是个文件
-r file检查file是否存在且可读
-s file检查file是否存在且非空
-w file检查file是否存在且可写
-x file检查file是否存在且可执行
-O file检查file是否存在且属当前用户所有
-G file检查file是否存在且默认组与当前用户相同
file1 -nt file2检查file1是否比file2新
file1 -ot file2检查file1是否比file2旧

检查目录

例:

#!/bin/bash
#Look before you leap
jump_directory=/home/keynes
if [ -d $jump_directory ]
then
	echo "The $jump_directory directory exists"
	cd $jump_directory
	ls
else
	echo "The $jump_directory directory does not exist"
fi

检查对象是否存在

例:

#!/bin/bash
# Check if either a directory or file exists
location=$HOME
file_name="dd"
if [ -e $location ]
then
	echo "OK on the filename"
	echo "Now checking on the file,$file_name"
	if [ -e $location/$file_name ]
	then
		echo "OK on the filename"
		echo "Updateing Current Date..."
		date >> $location/$file_name
	else
		echo "File does not exist"
		echo "Nothing to update"
	fi
else
	echo "The %location directory does not exist"
	echo "Nothing to update"
fi

检查文件

例:

#!/bin/bash
#Check if either a directory or file exist
item_name=$HOME
echo
echo "The item being checked:$item_name"
echo
if [ -e $item_name ]
then
	echo "The item,$item_name,does exist."
	echo "But is it a file?"
	echo
	if [ -f $item_name ]
	then
		echo "Yes,$item_name is a file"
	else
		echo "No,$item_name is not a file"
	fi
else
	echo "The item,$item_name,does not exist."
	echo "Nothing to update"
fi

检查是否可读

例:

#!/bin/bash
#testing if you can read a file
pwfile=/etc/shadow
if [ -f $pwfile ]
then
	if [ -r $pwfile ]
	then
		tail $pwfile
	else
		echo "Sorry,I am unable to read the $pwfile file"
	fi
else
	echo "Sorry,the file $pwfile does not exist"
fi

检查空文件

例:

#!/bin/bash
#Testing if a file is empty
file_name=$HOME/sentinel
if [ -f $file_name ]
then
	if [ -s $file_name ]
	then
		echo "The $file_name file exists and has data in it"
		echo "Will not remove this file."
	else
		echo "The $file_name file exists,but is empty"
		echo "Deleting empty file..."
		rm $file_name
	fi
else
	echo "File,$file_name does not exist."
fi

检查是否可写

例:

#!/bin/bash
#Check if a file is writable
item_name=$HOME/sentinel
echo
echo "The item being checked:$item_name"
echo
if [ -f $item_name ]
then
	echo "Yes,$item_name is a file."
	echo "But is it writable?"
	echo
	if [ -w $item_name ]
	then
		echo "Writing current time to $item_name"
		date +%H%M >> $item_name
	else
		echo "Unable to write to $item_name"
	fi
else
	echo "No,$item_name is not a file"
fi

检查文件是否可以执行

例:

#!/bin/bash
#testing file execution
if [ -x es16.sh ]
then
	echo "You can run the script:"
	./es16.sh
else
	echo "Sorry,you are unable to execute the script"
fi

检查所属关系

例:

#!/bin/bash
#check file ownership
if [ -O /etc/passwd ]
then
	echo "You are the owner of the /etc/passwd file"
else
	echo "Sorry,you are not the owner of the /etc/passwd file"
fi

检查默认属组关系

例:

#!/bin/bash
#check file group test
if [ -G $HOME/sentinel ]
then
	echo "You are in the same group as the file"
else
	echo "The file is not owned by your group"
fi

检查文件日期

例:

#!/bin/bash
#testing file dates
if [ es19.sh -nt es18.sh ]
then
	echo "The es19 file is newer than es18"
else
	echo "The es18 file is newer than es19"
fi

if [ es17.sh -ot es18.sh ]
then
	echo "The es17 file is older than es18"
else
	echo "The es18 file is older than es17"
fi

比较的前提是文件必须存在,否则将返回一个错误答案

例:

#!/bin/bash
#testing file dates
if [ badfile1 -nt badfile2 ]
then
	echo "The badfile1 file is newer than badfile2"
else
	echo "The badfile2 file is newer than badfile1"
fi

复合条件测试

[ condition1 ] && [ condition2 ]

[ condition1 ] || [ condition2 ]

例:

#!/bin/bash
#testing compound comparisons
if [ -d $HOME ] && [ -w $HOME/testing ]
then
	echo "The file exists and you can write to it"
else
	echo "I cannot write to the file"
fi

使用双括号

双括号命令用来使用高级数学表达式

双括号命令符号

符号描述
val++后增
val–后减
++val先增
–val先减
!逻辑求反
~位求反
**幂运算
<<左位移
>>右位移
&位布尔和
|位布尔或
&&逻辑和
||逻辑或

例:

#!/bin/bash
#using double parenthesis
val1=10
if (($val1**2>90))
then
	((val2=$val1**2))
	echo "The square of $val1 is $val2"
fi

使用双方括号

双方括号针对字符串比较

例:

#!/bin/bash
#using pattern matching
if [[ $USER == k* ]]
then
	echo "Hello $USER"
else
	echo "Sorry,I do not know you"
fi

case命令

例:

#!/bin/bash
#looking for a possible value
if [ $USER = "rich" ]
then
	echo "Welcome $USER"
	echo "Please enjoy your visit"
elif [ $USER = "barbara" ]
then
	echo "Welcome $USER"
	echo "Please enjoy your visit"
elif [ $USER = "testing" ]
then
	echo "Special testing account"
elif [ $USER = "jessica" ]
then
	echo "Do not forget to logout when you're done"
else
	echo "Sorry,you are not allowed here"
fi

for命令

for var in list
do
	commands
done

例:

#!/bin/bash
#basic for command
for test in Alabama Alaska Arizona Arkansas California Colorado
do
	echo The next state is $test
done

例:

#!/bin/bash
#testing the for variable after the looping
for test in Alabama Alaska Arizona Arkansas California Colorado
do
	echo "The next state is $test"
done
echo "The last state we visited was $test"
test=Connecticut
echo "Wait,now we're visiting $test"

使用转义字符来定义转义,使用双引号定义单引号的值

例:

#!/bin/bash
#another example of how not to use the for command
for test in I don\'t  know if "this'll" work
do
	echo "word:$test"
done

如果在单独的数据值中有空格,就必须用""将这些值圈起来

例:

#!/bin/bash
#an example of how to properly define values
for test in Nevada "New Hampshire" "New Mexico" "New York"
do
	echo "Now going to $test"
done

将一些列值集中存储到一个变量中

例:

#!/bin/bash
#using a variable to hold the list
list="Alabama Alask Arizona Arkansas Colorado"
list=$list" Connecticut"
for state in $list
do
	echo "Have you ever visited $state"
done

从命令读取值

例:

#!/bin/bash
#reading values from a file
file="tt"
for state in $(cat $file)
do
	echo "Visit beautiful $state"
done

更改字段分隔符(相当于split的分隔符)更改IFS环境变量的值

例:

#!/bin/bash
#reading values from a file
file="tt"
IFS=$'\n'
for state in $(cat $file)
do
	echo "Visit beautiful $state"
done

用通配符读取目录

例:

#!/bin/bash
#iterate through all the files in a directory
for file in /home/keynes/*
do
	if [ -d $file ]
	then
		echo "$file is a directory"
	elif [ -f $file ]
	then
		echo "$file is a file"
	fi
done

多个目录通配符

例:

#!/bin/bash
#iterating through multiple directories
for file in /home/keynes/.b* /home/keynes/
do
	if [ -d "$file" ]
	then
		echo "$file is a directory"
	elif [ -f "$file" ]
	then
		echo "$file is a file"
	else
		echo "$file doesn't exist"
	fi
done

C语言风格的for命令

例:

#!/bin/bash
#testing the C-style for loop
for((i=1;i<=10;i++))
do
	echo "The next number is $i"
done

使用多个变量

例:

#!/bin/bash
#multiple variable
for (( a=1,b=10;a<=10;a++,b--))
do
	echo "$a-$b"
done

while命令

例:

#!/bin/bash
#while command test
var1=10
while [ $var1 -gt 0 ]
do
	echo $var1
	var1=$[ $var1 - 1 ]
done

使用多个测试命令

例:

#!/bin/bash
#testing a multicommand while loop
var1=10
while echo $var1
		[ $var1 -ge 0 ]
do
	echo "This is inside the loop"
	var1=$[ $var1 - 1]
done

until命令

例:

#!/bin/bash
#using the until command
var1=100
until [ $var1 -eq 0 ]
do
	echo Inside the loop : $var1
	var1=$[ $var1 - 25 ]
done

例:

#!/bin/bash
#using the until c command
var1=100
until echo $var1
			[ $var1 -eq 0 ]
do
	echo Inside the loop:$var1
	var1=$[ $var1 -25 ]
done

嵌套循环

例:

#!/bin/bash
#nesting for loops
for((a=1;a<=3;a++))
do
	echo "Starting loop $a:"
	for((b=1;b<=3;b++))
	do
		echo "   Inside loop:$b"
	done
done

例:

#!/bin/bash
#placing a for loop inside a while loop
var1=5
while [ $var1 -ge 0 ]
do
	echo "Outer loop:$var1"
	for((var2=1;var2<3;var2++))
	do
		var3=$[ $var1*$var2 ]
		echo "   Inner loop:$var1*$var2=$var3"
	done
	var1=$[$var1-1]
done

例:

#!/bin/bash
#using until and while loops
var1=3
until [ $var1 -eq 0 ]
do
	echo "Outer loop:$var1"
	var2=1
	while [ $var2 -lt 5 ]
	do
		var3=$(echo "scale=4;$var1/$var2" | bc)
		echo "   Inner loop:$var1/$var2=$var3"
		var2=$[var2+1]
	done
	var1=$[$var1 - 1]
done

循环处理文件数据

#!/bin/bash
#changing the IFS value
IFS.OLD=$IFS
IFS='\n'
for entry in $(cat /etc/passwd)
do
	echo "Value in $entry -"
	IFS=:
	for value in $entry
	do
		echo "   $value"
	done
done

控制循环

break命令

  • 1.跳出单个循环

例:

#!/bin/bash
#breaking out of a for loop
for var1 in 1 2 3 4 5 6 7 8 9 10
do
	if [ $var1 -eq 5 ]
	then
		break
	fi
		echo "Iteration number:$var1"
done
echo "The loop is completed"

例:

#!/bin/bash
#breaking out of a while loop
var1=1
while [ $var1 -lt 10 ]
do
	if [ $var1 -eq 5 ]
	then
		break
	fi
	echo "Iteration:$var1"
	var1=$[ $var1 + 1 ]
done
echo "The while loop is completed"
  • 2.跳出内部循环

例:

#!/bin/bash
#breaking out of an inner loop
for((a=1;a<4;a++))
do
	echo "Outer loop:$a"
	for((b=1;b<100;b++))
	do
		if [ $b -eq 5 ]
		then
			break
		fi
		echo "   Inner loop:$b"
	done
done
  • 3.跳出外部循环

break n 其中n指定要跳出的循环层级

例:

#!/bin/bash
#breaking out of an outer loop
for((a=1;a<4;a++))
do
	echo "Outer loop:$a"
	for((b=1;b<100;b++))
	do
		if [ $b -gt 4 ]
		then
			break 2
		fi
		echo "   Inner loop:$b"
	done
done

continue命令

例:

#!/bin/bash
#using the continue command
for((var1=1;var1<15;var1++))
do
	if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
	then
		continue
	fi
	echo "Iteration number:$var1"
done

例:

#!/bin/bash
#improperly using the continue command in a while loop
var1=0
while echo "while iteration:$var1"
			[ $var1 -lt 15 ]
do
	if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
	then
		continue
	fi
	echo "   Inside iteration number:$var1"
	var1=$[$var1 +1]
done

continue n

例:

#!/bin/bash
#continuing an outer loop
for ((a=1;a<=5;a++))
do
	echo "Iteration $a"
	for ((b=1;b<3;b++))
	do
		if [ $a -gt 2 ] && [ $a -lt 4 ]
		then
			continue 2
		fi
		var3=$[ $a*$b ]
		echo "   The result of $a * $b is $var3"
	done
done

处理循环的输出

例:

#!/bin/bash
#redirecting the for output to a file
for((a=1;a<10;a++))
do
	echo "The number is $a"
	
done>test23.txt
echo "The command is finished"

例:

#!/bin/bash
#piping a loop to another command
for state in "North Dakota" Connecticut Illinois Alabama Tennessee
do
	echo "$state is the next place to go"
done | sort
echo "This completes our travels"

查找可执行文件

例:

#!/bin/bash
#find file in the PATH
IFS=:
for folder in $PATH
do
	echo "$folder:"
	for file in $folder/*
	do
		if [ -x $file ]
		then
			echo "   $file"
		fi
	done
done
举报

相关推荐

bash shell命令

0 条评论