Bash 脚本编程入门( 二 )


现在,创建一个新的 shell 脚本,命名为 arguments.sh,并向其中添加以下几行代码:
#!/bin/bashecho "Script name is: $0"echo "First argument is: $1"echo "Second argument is: $2"使其可执行并像这样运行它:
$ ./argument.sh abhishek prakashScript name is: ./argument.shFirst argument is: abhishekSecond argument is: prakash让我们快速看一下特殊变量:

Bash 脚本编程入门

文章插图
你也可以通过接受键盘输入使你的 Bash 脚本变得交互式 。
为此,你必须使用 read 命令 。你还可以使用 read -p 命令提示用户进行键盘输入,而不需要 echo 命令 。
#!/bin/bashecho "What is your name, stranger?"read nameread -p "What's your full name, $name? " full_nameecho "Welcome, $full_name"现在,如果你运行这个脚本,当系统提示你输入“参数”时,你必须输入 。
$ ./argument.shWhat is your name, stranger?abhishekWhat's your full name, abhishek? abhishek prakashWelcome, abhishek prakash
4、执行算术运算在 Bash Shell 中执行算术运算的语法是这样的:
$((arithmetic_operation))下面是你可以在 Bash 中执行的算术运算的列表:
Bash 脚本编程入门

文章插图
以下是在 Bash 脚本中进行加法和减法的示例:
#!/bin/bashread -p "Enter first number: " num1read -p "Enter second number: " num2sum=$(($num1+$num2))sub=$(($num1-$num2))echo "The summation of $num1 and $num2 is $sum"echo "The substraction of $num2 from $num1 is $sub"你可以执行 Shell 脚本,使用你选择的任意数字作为参数 。
Bash 脚本编程入门

文章插图
如果你尝试除法,会出现一个大问题 。Bash 只使用整数 。默认情况下,它没有小数的概念 。因此,你会得到 10/3 的结果为3,而不是 3.333 。
对于浮点数运算,你需要这样使用 bc 命令:
#!/bin/bashnum1=50num2=6result=$(echo "$num1/$num2" | bc -l)echo "The result is $result"这个时候,你将看到准确的结果 。
The result is 8.333333333333333333335、在 Bash 脚本中使用数组你可以使用 Bash 中的数组来存储同一类别的值,而不是使用多个变量 。
你可以像这样声明一个数组:
distros=(Ubuntu Fedora SUSE "Arch Linux" Nix)要访问一个元素,使用:
${array_name[N]}像大多数其他的编程语言一样,数组的索引从 0 开始 。
你可以像这样显示数组的所有元素:
${array[*]}这样获取数组长度:
${#array_name[@]}6、Bash 中的基础字符串操作Bash 能够执行许多字符串操作 。
你可以使用这种方式获取字符串长度:
${#string}连接两个字符串:
str3=$str1$str2提供子字符串的起始位置和长度来提取子字符串:
${string:$pos:$len}这里有一个例子:
Bash 脚本编程入门

文章插图
你也可以替换给定字符串的一部分:
${string/substr1/substr2}并且你也可以从给定字符串中删除一个子字符串:
${string/substring} 
Bash 基础知识系列 #6:处理字符串操作
 
7、在 Bash 中使用条件语句你可以通过使用 if 或 if-else 语句为你的 Bash 脚本添加条件逻辑 。这些语句以 fi 结束 。
单个 if 语句的语法是:
if [ condition ]; thenyour codefi注意使用 [ ... ]; 和 then  。
if-else 语句的语法是:
if [ expression ]; then## execute this block if condition is true else go to nextelif [ expression ]; then## execute this block if condition is true else go to nextelse## if none of the above conditions are true, execute this blockfi这里有一个使用 if-else 语句的 Bash 脚本示例:
#!/bin/bashread -p "Enter the number: " nummod=$(($num%2))if [ $mod -eq 0 ]; thenecho "Number $num is even"elseecho "Number $num is odd"fi 运行它,你应该能看到这样的结果:
Bash 脚本编程入门

文章插图
-eq 被称为测试条件或条件操作符 。有许多这样的操作符可以给你不同类型的比较:


推荐阅读