Bash Shell

!/bin/bash

chsh -s /bin/zsh 改变 /bin/bash 目录,不成功

chmod +x course_shell.sh 设置文件 x 属性

bash course_shell.sh 与 ./course_shell.sh 等效

变量设置

STR=”INDIA”

echo $STR

删除文件 输入文件名并确认 y/n

touch file1.txt file2.txt

echo -n “Enter name of file to delete:”

read file

echo Type ‘y’ to remove it, ‘n’ to change your mind…

rm -i $file

echo “That was YOUR decision!”

调用内部命令

LIST= ls

DATE= date

echo “Todays date is – ” $DATE

echo “The List of files are ” $LIST

四则运算

let X=10+2*7

let Y=X+2*4

echo X is $X

echo Y is $Y

P=”$((123+20))”

echo Answer is $P

VALUE=”$[123+20]”

echo VALUE is $VALUE

CUR_YEAR=date +"%Y"

echo -n “Enter your name:”

read NAME

echo -n “Enter your age:”

read AGE #let FIF_YEAR=(70-$AGE) +$CUR_YEAR

echo Hell $NAME !! You will be 70 years old in $FIF_YEAR

sudo mkdir /test00

cd /test00

sudo touch fi01 fi02 fi03

ls -l

echo “Folder test00 is created in current folder”

touch file01 file02 file03

echo “Files are created”

cd /test00

sudo rm -i fi02

ls -l

Shell Scription: Loops & Iterations

a=0

while [ “$a” -lt 10 ] #esterno loop

do

b=”$a”

while [ “$b” -ge 0 ] # interno loop

do

echo -n “$b “

b=expr $b -1

done

echo

a=expr $b - 1

done

Script to get specified numbers

read -p “Enter starting number: ” snum

read -p “Enter ending number: ” enum

#

while [[ $snum -le $enum ]];

do

echo $snum

((snum++))

done

#

echo “This is the sequence that you wanted.”

read -p “Enter starting number: ” snum

read -p “Enter ending number: ” enum

#

while [[ $snum -lt $enum || $snum == $enum ]];

do

echo $snum

((snum++))

done

#

echo “This is the sequence that you wanted.”

While Loop Example with a Break Statement

echo “Countdown for Website Launching…”

i=10

while [ $i -ge 1 ]

do

if [ $i == 2 ]

then

echo “Mission Aborted, Some Technical Error Found.”

break

fi

echo “$i”

(( i– ))

done

While Loop Example with a Continue Statement

i=0

while [ $i -le 10 ]

do

((i++))

if [[ “$i” == 5 ]];

then

continue

fi

echo “Current Number : $i”

done

#

echo “Skipped number 5 using Continue Statement.”

While loop example in C style

i=1

while((i <= 10))

do

echo $i

let i++

done

if elseif

read -p “输入数量:” num

#

if [ $num -gt 100 ];

then

echo “可以打9折.”

elif [ $num -lt 100 ];

then

echo “可以打9.5折.”

else

echo “幸运抽奖”

echo “有资格免费获得该物品”

fi

read -p “Enter a number of quantity:” num

#

if [ $num -gt 200 ];

then

echo “Eligible for 20% discount”

#

elif [[ $num == 200 || $num == 100 ]];

then

echo “Lucky Draw Winner”

echo “Eligible to get the item for free”

#

elif [[ $num -gt 100 && $num -lt 200 ]];

then

echo “Eligible for 10% discount”

#

elif [ $num -lt 100 ];

then

echo “No discount”

fi

Bash case语句

ex.1

echo “Do you know Kotlin Programming?”

read -p “Yes/No? :” Answer

case $Answer in

Yes|yes|y|Y)

echo “That’s amazing.”

echo

;;

No|no|N|n)

echo “It’s easy. Let’s start learning from yiibai.com.”

;;

esac

ex.2

echo “Which Operating System are you using?”

echo “Windows, Android, Chrome, Linux, Others?”

read -p “Type your OS Name:” OS

#

case $OS in

Windows|windows|window|win)

echo “That’s common. You should try something new.”

echo

;;

Android|android)

echo “This is my favorite. It has lots of applications.”

echo

;;

Chrome|chrome)

echo “Cool!!! It’s for pro users. Amazing Choice.”

echo

;;

Linux|linux)

echo “You might be serious about security!!”

echo

;;

*)

echo “Sounds interesting. I will try that.”

echo

;;

esac

#

Bash for循环

ex.1 This is the basic example of ‘for loop’.

learn=”Start learning from yiibai.com”

#

for l in $learn

do

echo $l

done

#

echo

echo “Thank You.”

#

ex.2 This is the basic example to print a series of numbers from 1 to 10.

#

for num in {1..10}

do

echo $num

done

#

echo “Series of numbers from 1 to 10.”

echo

#

ex.3 For Loop to Read a Range with Increment

#

for num in {1..10..1}

do

echo $num

done

#

echo

#

for num in {10..0..1}

do

echo $num

done

echo

#

ex.4 for循环读取数组变量

Array Declaration

arr=( “Welcome”,”to”,”yiibai.com” )

#

for i in “${arr[@]}”

do

echo “$i”

done

echo

#

For Loop to Read white spaces in String as word separators

for循环读取字符串中的空白作为单词分隔符=读取每个单词

str=”Let’s start

learning from yiibai.com.”

#

for s in $str;

do

echo “$s”

done

echo

#

ex.6 For Loop to Read each line in String as a word

for循环以单词形式读取字符串中的每一行=读取每一行

#

str=”Let’s start

learning from

yiibai.com.”

#

for i in “$str”;

do

echo “$i”

done

echo

#

ex.7 For Loop to Read Three-expression

for循环读取三表达式=经典 for 语句

for ((i=1; i<=10; i++))

do

echo “$i”

done

echo

#

ex.8 for循环与break语句

Table of 2

#

for table in {2..16..2}

do

echo $table

if [ $table == 8 ]; then

break

fi

done

echo

#

ex.9 Numbers from 1 to 20, ignoring from 6 to 15 using continue statement”

for循环与continue语句

for ((i=1; i<=20; i++));

do

if [[ $i -gt 5 && $i -lt 16 ]];

then

continue

fi

echo $i

done

echo

#

ex.10 for无限循环

i=1;

for (( ; ; ))

do

sleep 1s

echo “Current Number: $((i++))”

done

echo

Bash while循环

ex.1 单条件的While循环

Script to get specified numbers

read -p “Enter starting number: ” snum

read -p “Enter ending number: ” enum

#

while [[ $snum -le $enum ]];

do

echo $snum

((snum++))

done

#

echo “This is the sequence that you wanted.”

echo

#

Script to get specified numbers

ex.2 有多个条件的While循环

read -p “Enter starting number: ” snum

read -p “Enter ending number: ” enum

#

while [[ $snum -lt $enum || $snum == $enum ]];

do

echo $snum

((snum++))

done

#

echo “This is the sequence that you wanted.”

echo

#

ex.3 An infinite while loop

无限While循环

while :

do

echo “Welcome to Yiibai.”

sleep 1s

done

echo

上述脚本写成一行

An infinite while loop

while :; do echo “Welcome to Yiibai.”; done

#

An infinite while loop

#

while true

do

echo “Welcome to Yiibai”

done

#

ex. 4 While循环与Break语句

While Loop Example with a Break Statement

#

echo “Countdown for Website Launching…”

i=10

while [ $i -ge 1 ]

do

if [ $i == 2 ]

then

echo “Mission Aborted, Some Technical Error Found.”

break

fi

echo “$i”

(( i– ))

done

#

ex. 5 While循环与Continue语句

While Loop Example with a Continue Statement

#

i=0

while [ $i -le 10 ]

do

((i++))

if [[ “$i” == 5 ]];

then

continue

fi

echo “Current Number : $i”

done

#

echo “Skipped number 5 using Continue Statement.”

#

ex. 6 C语言样式while循环

While loop example in C style

#

i=1

while((i <= 10))

do

echo $i

let i++

done

Bash until循环

ex. 1 单条件until循环

Bash Until Loop example with a single condition

i=1
until [ $i -gt 10 ]
do
echo $i
((i++))
done

ex. 2 多条件until循环

Bash Until Loop example with multiple conditions

max=5
a=1
b=0

until [[ $a -gt $max || $b -gt $max ]];
do
echo “a = $a & b = $b.”
((a++))
((b++))
done

Bash字符串

等于运算符

Script to check whether two strings are equal.

str1=”xntutor.com”
str2=”yiibai.com”

if [ $str1 = $str2 ];
then
echo “Both the strings are equal.”
else
echo “Strings are not equal.”
fi

ex. 2 不等于运算符

Script to check whether two strings are equal.

str1=”yiibai.com”
str2=”xntutor.com”

if [[ $str1 != $str2 ]];
then
echo “Strings are not equal.”
else
echo “Strings are equal.”
fi

ex. 3 小于运算符

str1=”yiibai.com”
str2=”xntutor.com”
if [ $str1 \< $str2 ];
then
echo “$str1 is less then $str2”
else
echo “$str1 is not less then $str2”
fi

ex. 4 大于运算符

str1=”xntutor.com”
str2=”yiibai.com”
if [ $str1 > $str2 ];
then
echo “$str1 is greater then $str2”
else
echo “$str1 is less then $str2”
fi

ex. 5 检查字符串长度是否大于零

str=”WelcometoYiibai”

if [ -n $str ];
then
echo “String is not empty”
else
echo “String is empty”
fi

ex. 6 检查字符串长度是否等于零

str=””

if [ -z $str ];
then
echo “String is empty.”
else
echo “String is non-empty.”
fi

Bash查找字符串

ex. 1 #Bash program to find the length of a string

str=”Welcome to Yiibai.com”
length=${#str}

echo “Length of ‘$str’ is $length”

ex. 2 #Bash script to find the length of a string

str=”Welcome to Yiibai.com”
length=expr length "$str"

echo “Length of ‘$str’ is $length”

ex. 3 #Bash script to find the length of a string

str=”Welcome to Yiibai.com”
length=expr "$str" : '.*'

echo “Length of ‘$str’ is $length”

ex. 4 #Bash script to find the length of a string

str=”Welcome to Yiibai.com”
length=echo $str | wc -c

echo “Length of ‘$str’ is $length”

ex. 5 #Bash script to find the length of a string

str=”Welcome to xntutor.com”
length=echo $str |awk '{print length}'

echo “Length of ‘$str’ is $length”

Bash拆分字符串

ex. 1 Bash按空格分割字符串

Example for bash split string by space

read -p “Enter any string separated by space: ” str #reading string value

IFS=’ ‘ #setting space as delimiter
read -ra ADDR <<<“$str” #reading str as an array as tokens separated by IFS

for i in “${ADDR[@]}”; #accessing each element of array
do
echo “$i”
done

ex. 2 Bash按符号分割字符串

Example for bash split string by Symbol (comma)

read -p “Enter Name, City and Age separated by a comma: ” entry #reading string value

IFS=’,’ #setting comma as delimiter
read -a strarr <<<“$entry” #reading str as an array as tokens separated by IFS

echo “Name : ${strarr[0]} “
echo “City : ${strarr[1]} “
echo “Age : ${strarr[2]}”

不使用$IFS变量分割

ex. 1 Bash按符号分割字符串

Example for bash split string without $IFS

read -p “Enter any string separated by colon(:) ” str #reading string value

readarray -d : -t strarr <<<“$str” #split a string based on the delimiter ‘:’

printf “\n”

Print each value of Array with the help of loop

for (( n=0; n < ${#strarr[*]}; n++ ))
do
echo “${strarr[n]}”
done

ex. 2 使用字符串拆分字符串

Example for bash split string by another string

str=”WeLearnWelcomeLearnYouLearnOnLearnYiibai”
delimiter=Learn
s=$str$delimiter
array=();
while [[ $s ]];
do
array+=( “${s%%”$delimiter”}” ); s=${s#“$delimiter”};
done;
declare -p array

ex. 3 使用Trim命令分割字符串

Example to split a string using trim (tr) command

my_str=”We;welcome;you;on;yiibai!”
my_arr=($(echo $my_str | tr “;” “\n”))

for i in “${my_arr[@]}”
do
echo $i
done

Bash提取子字符串

Script to extract first 10 characters of a string

echo “String: We welcome you on Yiibai.”
str=”We welcome you on Yiibai.”

echo “Total characters in a String: ${#str} “

substr=”${str:0:10}”

echo “Substring: $substr”
echo “Total characters in Substring: ${#substr} “#ex. 1 从开始提取直到特定字符

ex. 2 从特定字符开始提取

Script to print from 11th character onwards

str=”We welcome you on Yiibai.”
substr=”${str:11}”
echo “$substr”

ex. 3 提取单个字符

Script to print 11th character of a String

str=”We welcome you on Yiibai.”
substr=”${str:11:1}”
echo “$substr”

ex. 4 从末尾提取特定字符

Script to extract 11 characters from last

str=”We welcome you on Yiibai.”
substr=”${str:(-11)}”
echo “$substr”

Bash连接字符串

ex. 1 并排写入变量连接

Script to Concatenate Strings

Declaring the first String

str1=”We welcome you”

Declaring the Second String

str2=” on Yiibai.”

Combining first and second string

str3=”$str1$str2″

Printing a new string by combining both

echo $str3

ex. 2 使用双引号连接

Script to Concatenate Strings

Declaring String Variable

str=”We welcome you”

Add the variable within the string

echo “$str on Yiibai.”

ex. 3 将追加运算符与循环一起使用连接

echo “Printing the name of the programming languages”

Initializing the variable before combining

lang=””

for loop for reading the list

for value in ‘java’ ‘python’ ‘C’ ‘C++’ ‘Bash’;
do
lang+=”$value ” #Combining the list values using append operator
done

Printing the combined values

echo “$lang”

ex. 4 使用Printf函数连接

str=”Welcome”
printf -v new_str “$str to Yiibai.”
echo $new_str

ex. 5 使用文字字符串连接

str=”Welcome to”

newstr=”${str} Yiibai.”
echo “$newstr”

ex. 6 使用下划线连接

str1=”Hello”
str2=”World!”

echo “${str1}_${str2}”

ex. 7 使用任意字符连接

String Concatenation by Character (,) with User Input

read -p “Enter First Name: ” name
read -p “Enter City: ” state
read -p “Enter Age: ” age

combine=”$name,$state,$age”

echo “Name, City, Age: $combine”

Bash函数

ex. 1

welcome () {
echo ‘Welcome to Yiibai.’
}

welcome

ex. 2

function welcome () {
echo ‘Welcome to Yiibai.’
}

welcome

传递参数

给定的参数以$1,$2,$3,…$n的形式访问,对应于函数名后参数的位置。

$0变量的值是函数的名称。

$#变量用于保存赋予函数的位置自变量/参数的数量。

$*和$@变量用于保存赋予函数的所有参数。

当$与双引号(即”$“)一起使用时,它将扩展为一个由空格分隔的字符串。

例如,”$1 $2 $n”等。

当$@与双引号(即”$@”)一起使用时,它将扩展为单独的字符串。

例如,”$1″ “$2” “$n”等。

当$*和$#不与双引号一起使用时,它们都是相同的。

Bash脚本

Script to pass and access arguments

function_arguments(){
echo $1
echo $2
echo $3
echo $4
echo $5
}

Calling function_arguments

function_arguments “We” “welcome” “you” “on” “Yiibai”

变量的作用域

v1=’A’
v2=’B’

my_var () {
local v1=’C’
v2=’D’
echo “Inside Function”
echo “v1 is $v1.”
echo “v2 is $v2.”
}

echo “Before Executing the Function”
echo “v1 is $v1.”
echo “v2 is $v2.”

my_var
echo “After Executing the Function”
echo “v1 is $v1.”
echo “v2 is $v2.”

返回值

ex. 1 Setting up a return status for a function

print_it () {
echo Hello $1
return 5
}

print_it User
print_it Reader
echo The previous function returned a value of $?

ex. 2

print_it () {
local my_greet=”Welcome to Yiibai.”
echo “$my_greet”
}

my_greet=”$(print_it)”
echo $my_greet

覆盖命令

Script to override command using function

echo () {
builtin echo -n date +"[%m-%d %H:%M:%S]" “: “
builtin echo $1
}

echo “Welcome to Yiibai.”

Bash数组

1. 数字索引数组

declare -a ARRAY_NAME

2. 关联数组

declare -A ARRAY_NAME

3. Bash数组初始化

ARRAY_NAME=(element_1st element_2nd element_Nth)

4. Bash数组的访问元素

echo ${ARRAY_NAME[2]}

Bash打印数组

declare -p ARRAY_NAME

数组运算

引用元素

Script to print an element of an array with an index of 2

declaring the array

declare -a example_array=( “Welcome” “To” “Yiibai” )

printing the element with index of 2

echo ${example_array[2]}

打印所有元素

Script to print all the elements of the array

declaring the array

declare -a example_array=( “Welcome” “To” “Yiibai” )

Printing all the elements

echo “${example_array[@]}”

使用@和*之间的唯一区别是,使用@时,需要使用双引号引起来

echo “${example_array[@]}”

使用 for + @循环

for i in “${example_array[@]}”; do echo “$i”; done

打印数组的键 索引

Script to print the keys of the array

Declaring the Array

declare -a example_array=( “Welcome” “To” “Yiibai” )

Printing the Keys

echo “${!example_array[@]}”

查找数组长度

Declaring the Array

declare -a example_array=( “Welcome” “To” “Yiibai” )

Printing Array Length

echo “The array contains ${#example_array[@]} elements”

遍历数组

Script to print all keys and values using loop through the array

declare -a example_array=( “Welcome” “To” “Yiibai” )

Array Loop

for i in “${!example_array[@]}”
do
echo The key value of element “${example_array[$i]}” is “$i”
done

C语言样式的循环

Script to loop through an array in C-style

declare -a example_array=( “Welcome” “To” “Yiibai” )

Length of the Array

length=${#example_array[@]}

Array Loop

for (( i=0; i < ${length}; i++ ))
do
echo $i ${example_array[$i]}
done

将元素添加到数组

Declaring an array

ex. 1

declare -a example_array=( “Java” “Python” “PHP” “HTML” )

Adding new element

example_array[4]=”JavaScript”

Printing all the elements

echo “${example_array[@]}”

ex. 2

Declaring the Array

declare -a example_array=( “Java””Python””PHP” )

Adding new elements

example_array+=( JavaScript CSS SQL )

Printing all the elements

echo “${example_array[@]}”

更新数组元素

Script to update array element

Declaring the array

declare -a example_array=( “We” “welcome” “you” “on” “nxtutor.com” )

Updating the Array Element

example_array[4]=Yiibai

Printig all the elements of the Array

echo ${example_array[@]}

从数组中删除元素

Script to delete the element from the array

Declaring the array

declare -a example_array=( “Java” “Python” “HTML” “CSS” “JavaScript” )

Removing the element

unset example_array[1]

Printing all the elements after deletion

echo “${example_array[@]}”

删除整个数组

Script to delete the entire Array

Declaring the Array

declare -a example_array=( “Java” “Python” “HTML” “CSS” “JavaScript” )

Deleting Entire Array

unset example_array

Printing the Array Elements

echo ${!example_array[@]}

Printing the keys

echo ${!example_array[@]}

切片数组元素 SLICED_ARRAY=(${ARRAY_NAME[@]:m:n}”)

Script to slice Array Element from index 1 to index 3

Declaring the Array

example_array=( “Java” “Python” “HTML” “CSS” “JavaScript” )

Slicing the Array

sliced_array=(“${example_array[@]:1:3}”)

Applying for loop to iterate over each element in Array

for i in “${sliced_array[@]}”
do
echo $i
done

Bash读取文件

使用 cat fileName 读取文件 value=cat file_name

ex. 1

value=cat read_file.txt
echo “$value”

ex. 2 使用 $(fileName) 读取文件 value=$(file_name)

value=$(<read_file.txt)
echo “$value”

ex. 3 从命令行读取文件内容 while read line; do Command; done < input.file

while read line; do echo $line; done < read_file.txt

ex. 4 使用脚本读取文件内容

file=’read_file.txt’

i=1
while read line; do

Reading each line

echo “Line No. $i : $line”
i=$((i+1))
done < $file

ex. 5 从命令行传递文件名并读取文件

file=$1
while read line; do

Readind each line in sequence

echo $line
done <read_file.txt

ex. 6 通过省略反斜杠转义来读取文件

while read -r line; do

Reading each line by omitting backslash escape

echo $line
done < read_file.txt

Bash写入文件

ex. 1 仅将输出写入文件

Script to write the output into a file

Create output file, override if already present

output=output_file.txt

Write data to a file

ls > $output

Checking the content of the file

gedit output_file.txt

将文件的内容打印到终端

Script to write the output into a file

Create output file, override if already present

output=output_file.txt

Write data to a file

ls > $output

Printing the content of the file

cat $output

将多个命令的输出重定向到单个文件

Script to write the output into a file

Create output file, override if already present

output=output_file.txt

Write data to a file

ls > $output

Appending the system information

uname -a >> $output

Checking the content of the file

gedit output_file.txt

上面,uname -a >> $output 命令的结果将附加到文件末尾

ex. 2 打印输出并写入文件

Script to write the output into a file

Create output file, override if already present

output=output_file.txt

Write data to a file

ls | tee $output

与>运算符一样,它将覆盖文件的原内容,但也会在屏幕上打印输出。如果要在不使用tee命令删除文件内容的情况下将输出写入文件,则可以使用以下格式将输出打印到终端,参考以下代码

Script to write the output into a file

Create output file, override if already present

output=output_file.txt

echo “<<>>” | tee -a $output

Write data to a file

ls | tee $output

echo | tee -a $output

Append System Information to the file

echo “<<>>” | tee -a $output
uname | tee -a $output

end

Scroll to Top