1. 首页 > 数码 >

shell语法(shell中的while循环)

本文目录一览:

shell脚本中的if中多条件语句如何写。

可以使用 if-elif-else 语法来写多条件语句。

shell语法(shell中的while循环)shell语法(shell中的while循环)


1、首先要理解if-else的基本用法,if条件+then作+else作+fi闭合,书写方法如下:

2、if -elif-else 语法的具体格式--if单条件多分支,书写方法如下:

3、实例 - if单条件多分支,这个实例的输出结果是:a 小于 b。

4、实例 - if多条件多分支,这个实例输出结果是:a 等于 b,或 a小于10。

扩展资料

1、shell语法注意事项

shell的if语法和C语言等高级语言非常相似,需要注意的地方就是shell的if语句对空格方面的要求比较严格,如果在需要空格的地方没有打上空格,就会报错。

如if [ 1 == 1 ];then echo "abc";fi中如果在少写了if后面的空格就报错:

2、 shell语法中[[ ]]和[ ]的主要区别

(1) [ ] 实际上是bash 中 test 命令的简写。即所有的 [ expr ] 等于 test expr。

对 test 命令来说, 用 -eq 要进行数字比较,而你此时传入字符串,就报错了。

(2) [[ ]] 是内置在shell中的一个命令,它比test强大的多。支持字符串的模式匹配(使用=~作符时甚至支持shell的正则表达式)。逻辑组合可以不使用test的-a,-o而使用 ||。

关于shell script的几个语法点

关于shell script的几个语法一些摘录与总结

一、双引号与单引号的区别

根据GNU bash manual,各自有一下含义:

1、单引号

Enclosing charactersin single quotes (') preserves the literal value of each character within thequotes. A single quote may not occur between single quotes, n when precededby a backslash.

2、双引号

Enclosing characters in double quotes (")preserves the literal value of all characters within the quotes, with theexception of $, `, \, and, when history expansion is enabled, !. The characters$ and ` retain their special meaning within double quotes (see ShellExpansions). The backslash retains its special meaning only when followed byone of the following characters: $, `, ", \, or newline. Within doublequotes, backslashes that are followed by one of these characters are removed.Backslashes preceding characters without a special meaning are left unmodified.A double quote may be quoted within double quotes by preceding it with abackslash. If enabled, history expansion will be performed unless an !appearing in double quotes is escaped using a backslash. The backslashpreceding the ! is not removed.

The special parameters and @ he special meaningwhen in double quotes (see Shell Parameter Expansion).

3、相关表格

The accepted answer is great. I am a tablat s in quick comprehension of the topic. The explanation involves a variable a as well as an indexed array arr.

If we set

a=apple     # a variable

arr=(apple) # an indexed array with a single element

and then echo theexpression in the second column, we would get the result / behior shown inthe third column. The fourth column explains the behior.

# |Expression  | Result      | Comments

---+-------------+-------------+--------------------------------------------------------------------

 1 | "$a"        | apple       | variables are expanded inside""

 2 | '$a'       | $a          | variables are notexpanded inside ''

 3 | "'$a'"      | 'apple'     | '' has no special meaning inside""

 4 | '"$a"'      | "$a"        | "" is treated literallyinside ''

 5 | '\''       | invalid | can not escape a ' within ''; use "'" or $'\''(ANSI-C quoting)

 6 | "red$arocks"| red         | $arocks does not expand $a; use${a}rocks to preserve $a

 7 | "redapple$" | redapple$   | $ followed by no variable name evaluatesto $

 8 | '\"'        | \"          | \ has no special meaning inside ''

 9 | "\'"        | \'          | \' is interpreted inside"" but has no significance for '

10 |"\""        | "           | \" is interpreted inside""

11 |""         |            | glob does not work inside"" or ''

12 |"\t\n"      | \t\n        | \t and \n he no special meaning inside"" or ''; use ANSI-C quoting

13 | "`echohi`" | hi          | `` and $() areevaluated inside ""

14 | '`echo hi`' |`echo hi`   | `` and $() are notevaluated inside ''

15 | '${arr[0]}' |${arr[0]}   | array access not sibleinside ''

16 | "${arr[0]}"| apple       | array access works inside""

17 | $'$a\''     | $a'         | single quotes can be escaped insideANSI-C quoting

18 |"$'\t'"     | $'\t'       | ANSI-C quoting is not interpretedinside ""

19 | '!cmd'      | !cmd        | history expansion character '!' isignored inside ''

20 |"!cmd"      | cmd args    | expands to the most recent commandmatching "cmd"

21 | $'!cmd'     | !cmd        | history expansion character '!' isignored inside ANSI-C quotes

二、双圆括号与单圆括号区别

()括号内运行一个subshell,$()返回subshell结果

ex( grep ABC file1; grep XYZ file1 ) | wc -l

(())括号内进行数算,$(())返回数算的结果

较为专业的解释是:

It is a syntax concession to maintain backward compatibility forscripts.

The (()) formation ls the bash interpreter to use internaloperations - otherwise it can’t (or won’t) find the necessary tools to theevaluation.

如果不使用(()),譬如

NUM1=3

NUM2=5

Sum=$NUM1+$NUM2

echo “Sum = $Sum”

得到 Sum = 3+5,成了字符串concatenation。

三、双圆方括号与单圆方括号区别

Single [] are ix shell compliant condition tests.

Double [[]] are an extension to the standard [] and are supported bybash and other shells (e.g. zsh, ksh). They support extra operations (as wellas the standard ix operations). For example: || instead of -o and regexmatching with =~. A fuller list of differences can be found in the bash manualsection on conditional constructs.

Use [] whenr you want your script to be portable across shells.Use [[]] if you want conditional expressions not supported by [] and don't needto be portable.

四、大括号含义

${}返回大括号内shell script的变量值

In this particular example, it makes no difference. Howr, the {}in ${} are useful if you want to expand the variable foo in the string

"${foo}bar"

since "$foobar" would instead expand the variableidentified by foobar.

Cy braces are also unconditionally required when:

    expanding array elements,as in ${array[42]}

    using parameter expansionoperations, as in ${filename%.} (remove extension)

    expanding itionalparameters beyond 9: "$8 $9 ${10} ${11}"

Doing this rywhere, instead of just in potentially ambiguouscases, can be considered good programming pract. This is both forconsistency and to oid surprises like $foo_$bar.jpg, where it's not visuallyobvious that the underscore becomes part of the variable name.

五、其他

Generally $var gives the value of var.

iOS开发-需要了解的Shell脚本语法

Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。Shell 脚本(shell script),是一种为 shell 编写的脚本程序。在iOS开发中,我们通常编写一些自动化的脚本文件,来提高我们的生产效率,其本质就是通过Shell脚本对一些 xcodebuild , xcode-select , xcpretty , xcrun 等指令的封装。本篇文章,我们就针对 Shell 脚本的语法,做一些罗列,以辅助我们去完成一些自动化封装。

执行脚本

.sh 文件为 Shell 脚本文件格式,通过 sh 指令执行脚本文件

执行结果:

1.通过 echo 输出变量时,需要使用 $ 或者 ${} 修饰

2. (重点)定义变量时,等号之间不能有空格,不然会误认为变量为一个指令

3.可以直接修改 name 变量的值,即当前 name 默认为 readwrite 权限

4.我们给 _var 用 readonly 修饰后,再修改值会抛出异常

执行结果:

执行结果:

执行结果:

执行结果:

$@ 和 $ 都是输出所有参数,前者是 "$1" "$2" "$3" "$4" ,后者是 "$1 $2 $3 $4"

执行结果:

注意:条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [ $a == $b ] 。

关于文件检测运算符,这里还是都罗列一下吧,比较重要:

执行结果:

执行结果:

执行结果:

执行结果:

2.有参数

执行结果:

注意: $10 不能获取第十个参数,获取第十个参数需要 ${10} .

使用 man 查询 指令文档

比如我们想查看 xcodebuild 指令下都有哪些作,直接在终端执行:

当我们不清楚某一个指令下的作时,就可以通过 man 查询,然后辅助我们来编写 Shell 指令。

在iOS下,了解下这些 Shell 语法就足够了,已经可以帮助我们完成大部分的 Shell脚本 的编写或者阅读别人的 Shell 源码。不需要记忆,简单看下就可以。

shell知识点

一些经典的 Shell 脚本面试问题 - CSDN博客

1. 如何在脚本中使用参数 ?

个参数 : $1,第二个参数 :$2

例子 : 脚本会文件(arg1) 到目标地址(arg2)

./copy.sh file1.txt /tmp/

cat copy.sh

#!/bin/bash

cp $1 $2

2. 如何计算传递进来的参数 ?

$#

3. 如何检查之前的命令是否运行成功?

$?

4. 如何获取文件的一行 ?

tail -1

5. 如何获取文件的行 ?

head -1

6. 如何获取一个文件每一行的第三个元素 ?

awk'{print $3}'

7. 如文件中每行个元素是FIND,如何获取第二个元素

awk'{ if ($1 == "FIND") print$2}'

8. 如何调试 bash 脚本

将 -xv 参数加到#!/bin/bash 后

例子:

#!/bin/bash –xv

9. 举例如何写一个函数 ?

function example {

echo "Hello world!"

}

10. 如何向连接两个字符串 ?

V1="Hello"

V2="World"

V3=${V1}${V2}

echo $V3

输出

HelloWorld

11. 如何进行两个整数相加 ?

V1=1

V2=2

let V3=$V1+$V2

echo $V3

输出

3

12. 如何检查文件系统中是否存在某个文件 ?

if [ -f /var/log/messages ]

then

echo "File exists"

fi

13. 写出 shell 脚本中所有循环语法 ?

for 循环 :

foriin$(ls);do

echo :$i

done

while 循环 :

#!/bin/bash

COUNTER=0

while [ $COUNTER -lt 10 ]; do

echo The counter is $COUNTER

let COUNTER=COUNTER+1

done

until 循环 :

#!/bin/bash

COUNTER=20

until [ $COUNTER -lt 10 ]; do

echo COUNTER $COUNTER

let COUNTER-=1

done

14. 每个脚本开始的#!/bin/sh 或 #!/bin/bash 表示什么意思?

这一行说明要使用的 shell。#!/bin/bash表示脚本使用 /bin/bash。对于 python 脚本,就是 #!/usr/bin/python。

15. 如何获取文本文件的第 10 行 ?

head -10 file|tail -1

16. bash 脚本文件的个符号是什么

#

17. 命令:[ -z"" ] echo 0 || echo 1 的输出是什么

18. 如何在后台运行脚本 ?

nohup command

19. "chmod 500 script" 做什么 ?

使脚本所有者拥有可执行权限。

20.  "" 做什么 ?

重定向输出流到文件或另一个流。

21. 和 有什么区别

- 希望脚本在后台运行的时候使用它

- 当前一个脚本成功完成才执行后面的命令/脚本的时候使用它

22. bash shell 脚本中哪个符号用于注释 ?

#

23. ' 和 " 引号有什么区别 ?

' - 当我们不希望把变量转换为值的时候使用它。

" - 会计算所有变量的值并用值代替。

24. 如何在脚本文件中重定向标准输出和标准错误流到log.txt 文件 ?

在脚本文件中添加 "exec log.txt21" 命令。

25. 如何只用 echo 命令获取字符串变量的一部分 ?

echo ${variable:x:y}

x - 起始位置

y - 长度

例子:

variable="My name is Petras, and I amdloper."

echo ${variable:11:6} # 会显示 Petras

26. 如何使用 awk 列出 UID 小于 100 的用户 ?

awk -F: '$3100' /etc/passwd

27. 写程序为用户计算主组数目并显示次数和组名

cat /etc/passwd|cut -d: -f4|sort|uniq-c|while read c g

do

{ echo $c; grep :$g: /etc/group|cut -d:-f1;}|xargs -n 2

done

28. 如何获取变量长度 ?

${#variable}

29. 如何打印变量的 5 个字符 ?

echo ${variable: -5}

30. 如何只用 echo 命令替换字符串的一部分 ?

echo ${variable//pattern/replacement}

31. 如何计算本地用户数目 ?

wc -l /etc/passwd|cut -d" " -f1 或者 cat /etc/passwd|wc -l

32. 不用 wc 命令如何计算字符串中的单词数目 ?

set ${string}

echo $#

33. 如何列出第二个字母是 a 或 b 的文件 ?

ls -d ?[ab]

34. 如何将整数 a 加到 b 并赋值给 c ?

c=$((a+b))

c=`expr $a + $b`

c=`echo "$a+$b"|bc`

35. 如何去除字符串中的所有空格 ?

echo $string|tr -d " "

36. 写出输出数字 0 到 100 中 3 的倍数(0 3 6 9…)的命令 ?

for i in {0..100..3}; do echo $i; done

for (( i=0; i=100; i=i+3 )); do echo"Welcome $i times"; done

37. 如何打印传递给脚本的所有参数?

echo $

echo $@

38.  [ $a == $b ] 和[ $a -eq $b ] 有什么区别

[ $a == $b ] - 用于字符串比较

[ $a -eq $b ] - 用于数字比较

39. = 和 == 有什么区别

= - 用于为变量赋值

== - 用于字符串比较

40. 写出测试 $a 是否大于 12 的命令 ?

[ $a -gt 12 ]

41. 如何检查字符串是否以字母"abc" 开头 ?

[[ $string == abc ]]

42. [[ $string == abc ]] 和 [[ $string == "abc" ]] 有什么区别

[[ $string == abc ]] - 检查字符串是否以字母 abc 开头

[[ $string == "abc" ]] - 检查字符串是否完全等于 abc

43. 如何列出以 ab 或 xy 开头的用户名 ?

egrep "^ab|^xy" /etc/passwd|cut-d: -f1

44. bash 中 $! 表示什么意思 ?

后台最近执行命令的 PID.

45. $? 表示什么意思 ?

前台最近命令的结束状态。

46. 如何输出当前 shell 的 PID ?

echo $$

47. $ 和 $@ 有什么区别

$ - 以一个字符串形式输出所有传递到脚本的参数

$@ - 以 $IFS 为分隔符列出所有传递到脚本中的参数

48. 如何在 bash 中定义数组 ?

array=("Hi" "my""name" "is")

49. 如何打印数组的个元素 ?

echo ${array[0]}

50. 如何打印数组的所有元素 ?

echo ${array[@]}

51. 如何输出所有数组索引 ?

echo ${!array[@]}

52. shell 脚本如何获取输入的值 ?

a) 通过参数

./script param1 param2

b) 通过 read 命令

read -p "Destination backup :" desthost

LINUX快速入门第八章:Shell基础

我们平时所说的 Shell 可以理解为 Linux 系统提供给用户的使用界面。Shell 为用户提供了输入命令和参数并可得到命令执行结果的环境。当一个用户登录 Linux 之后,系统初始化程序 init 就根据 /etc/passwd 文件中的设定,为每个用户运行一个被称为 Shell(外壳)的程序。

确切地说,Shell 是一个命令行解释器,它为用户提供了一个向 Linux 内核发送请求以便运行程序的界面系统级程序,用户可以用 Shell 来启动、挂起、停止甚至编写一些程序。

Shell 处在内核与外层应用程序之间,起着协调用户与系统的一致性、在用户与系统之间进行交互的作用。图 1 是 Linux 系统层次结构图,Shell 接收用户输入的命令,并把用户的命令从类似 abed 的 ASCII 码解释为类似 0101 的机器语言,然后把命令提交到系统内核处理;当内核处理完毕之后,把处理结果再通过 Shell 返回给用户。

换句话说:

Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。

Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问作系统内核的服务。

Ken Thompson 的 sh 是种 Unix Shell,Windows Explorer 是一个典型的图形界面 Shell。

Shell 与其他 Linux 命令一样,都是实用程序,但它们之间还是有区别的。一旦用户注册到系统后,Shell 就被系统装入内存并一直运行到用户退出系统为止;而一般命令仅当被调用时,才由系统装入内存执行。

与一般命令相比,Shell 除了是一个命令行解释器,同时还是一门功能强大的编程语言,易编写,易调试,灵活性较强。作为一种命令级语言,Shell 是解释性的,组合功能很强,与作系统有密切的关系,可以在 Shell 脚本中直接使用系统命令。大多数 Linux 系统的启动相关文件(一般在 /etc/rc.d 目录下)都是使用 Shell 脚本编写的。

同传统的编程语言一样,Shell 提供了很多特性,这些特性可以使 Shell 脚本编程更为有用,如数据变量、参数传递、判断、流程控制、数据输入和输出、子程序及中断处理等。

说了这么多,其实我们在 Linux 中作的命令行界面就是 Linux 的 Shell,也就是 Bash,但是我们的图形界面是 Shell 吗?其实从广义讲,图形界面当然也是 Shell,因为它同样用来接收用户的作,并传递到内核进行处理。不过,这里的 Shell 主要指的是 Bash。

Shell 脚本

Shell 脚本(shell script),是一种为 shell 编写的脚本程序。

业界所说的 shell 通常都是指 shell 脚本,但读者朋友要知道,shell 和 shell script 是两个不同的概念。

由于习惯的原因,简洁起见,本文出现的 "shell编程" 都是指 shell 脚本编程,不是指开发 shell 自身。

Shell的分类

目前 Shell 的版本有很多种,如 Bourne Shell、C Shell、Bash、ksh、tcsh 等,它们各有特点,下面简要介绍一下。

最重要的 Shell 是 Bourne Shell,这个命名是为了纪念此 Shell 的发明者 Stn Bourne。从 1979 年起,UNIX 就开始使用 Boume Shell。Bourne Shell 的主文件名为 sh,开发人员便以 sh 作为 Bourne Shell 的主要识别名称。

虽然 Linux 与 UNIX 一样,可以支持多种 Shell,但 Boume Shell 的重要地位至今仍然没有改变,许多 UNIX 系统中仍然使用 sh 作为重要的管理工具。它的工作从开机到关机,几乎无所不包。在 Linux 中,用户 Shell 主要是 Bash,但在启动脚本、编辑等很多工作中仍然使用 Bourne Shell。

C Shell 是广为流行的 Shell 变种。C Shell 主要在 BSD 版的 UNIX 系统中使用,发明者是柏克莱大学的 Bill Joy。C Shell 因为其语法和 C 语言类似而得名,这也使得 UNIX 的系统工程师在学习 C Shell 时感到相当方便。

Bourne Shell 和 C Shell 形成了 Shell 的两大主流派别,后来的变种大都吸取这两种 Shell 的特点,如 Korn、 tcsh 及 Bash。

Bash Shell 是 GNU 的重要工具之一,也是 GNU 系统中标准的 Shell。Bash 与 sh 兼容,所以许多早期开发出来的 Bourne Shell 程序都可以继续在 Bash 中运行。现在使用的 Linux 就使用 Bash 作为用户的基本 Shell。

Bash 于 1988 年发布,并在 1995-1996年推出Bash 2.0。在这之前,广为使用的版本是1.14,Bash 2.0增加了许多新的功能,以及具备更好的兼容性。表 2 中详细列出了各版本的具体情况。

注意,Shell 的两种主要语法类型有 Bourne 和 C,这两种语法彼此不兼容。Boume 家族主要包括 sh、ksh、Bash、psh、zsh;C 家族主要包括 csh、tcsh(Bash 和 zsh 在不同程序上支持 csh 的语法)。

本章讲述的脚本编程就是在 Bash 环境中进行的。不过,在 Linux 中除了可以支持 Bash,还可以支持很多其他的 Shell。我们可以通过 /etc/shells 文件来査询 Linux 支持的 Shell。命令如下:

在 Linux 中,这些 Shell 是可以任意切换的,命令如下:

用户信息文件 /etc/passwd 的一列就是这个用户的登录 Shell。命令如下:

大家可以看到,root 用户和其他可以登录系统的普通用户的登录 Shell 都是 /bin/bash,也就是 Linux 的标准 Shell,所以这些用户登录之后可以执行权限允许范围内的所有命令。不过,所有的系统用户(伪用户)因为登录 Shell 是 /in/ndogin,所以不能登录系统。

笔记:

sh/bash/csh/Tcsh/ksh/pdksh等shell的区别

Shell 中 if 语句的使用

Shell 的 if 语法 和 C 语言等高级语言非常相似,需要注意的地方就是 Shell 的 if 语句对 空格 方面的要求比较严格( 其实 Shell 对所有语法的空格使用都比较严格 ),如果在需要空格的地方没有打上空格,都会报错。如: if [ $1 == "ip" ];then echo "abc"; fi 中少了一个空格都会报错。另外 Shell 的 if 语句必须以 fi 作为结尾,不然同样会报错。

有 else 和 elif 时也一样,需要注意空格问题,下面这个例子可以作为参考

介绍完 if 语句的基本语法后,if 还有一个值得我们注意的地方,那就是"对比"。在 C 语言等高级语言中,不管是对比字符串,还是对比整型、浮点数等等数据类型,都是使用 ==、= 等等对比运算符就可以完成。但是在 Shell 中对比字符串和对比数字,却是要分开两种方式。

对比字符串只能使用 ==、、、!=、-z、-n 。对比字符串时,末尾一定要加上 x(或者a、b等)一个字符,因为 if [ 1 是"",这个语句会翻译成 if [ == "ab" ] ,左边相当于没有东西了,会报语法错误。或者使用 [[ ]] ,就不需要 x 了。使用 或者 时,如果是用 [ ],需要用转义符 "",如 。

对比数字既能使用 -eq、-ne、-gt、-lt、-le ,也能使用 ==、、、!= 。其中 -eq 的意思是 equal,-ne 是 unequal,-gt 是 greater than,-ge 是 greater than or equal to,-lt 是 less than,-le 是 less than or equal to 。

if 在对比时可以使用正则表达式,如: if [[ $1 == aa ]] (或者 if [ $1x == aax) 。如果使用 "" 把 a a 包围起来, 就会变成字符 ,而不是正则表达式的 。

区别一:

在 [ 中使用逻辑运算符,需要使用 -a(and)或者 -o(or)。

在 [[ 中使用逻辑运算符,需要使用 或者 ||。

区别二:

[ 是 Shell 命令,它包围的表达式是它的命令行参数,所以字符串比较符 和 需要转义,否则就变成 io 重定向了。

[[ 是 Shell 关键字,不会做命令扩展,所以 和 不需要进行转义。但是语法相对严格,如在 [ 中可以用引号括起作符,[[ 则不行。如: if [ "-z" "ab" ] 。

区别三:

[[ 可以做算术扩展,[ 则不行。如:```if [[ 11 + 1 -eq 100 ]]''',而 '''if [ 11 + 1 -eq 100 ]''' 则会报错。

在高级语言中,判断文件是否存在等各种状态都是需要调用特定的函数进行判断。而在 Shell 中,这方面就比较方便些,只需要运算符即可。

常用的文件判断运算符如下:

原文:

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 12345678@qq.com 举报,一经查实,本站将立刻删除。

联系我们

工作日:9:30-18:30,节假日休息