Linux shell编程笔记
第一行
#!/bin/sh # 指定脚本解释器,这里是用/bin/sh做解释器的
cd ~ # 切换到当前用户的home目录
可以切换sh
[dev@szvphispra72471 ~]$ ls -l /bin/*sh
-rwxr-xr-x. 1 root root 1215888 Apr 1 2019 /bin/bash
-rws--x--x. 1 root root 68856 Apr 1 2019 /bin/chsh
lrwxrwxrwx. 1 root root 4 Apr 1 2019 /bin/csh -> tcsh
-r-x------. 1 root root 377 Apr 1 2019 /bin/euleros_kdump_do_post.sh
-r-x------. 1 root root 112 Apr 1 2019 /bin/euleros_kdump_do_pre.sh
-rwxr-xr-x. 1 root root 4632 Apr 1 2019 /bin/gettext.sh
-rwxr-xr-x. 1 root root 32 Apr 1 2019 /bin/hash
-rwxr-xr-x. 1 root root 4194 Apr 1 2019 /bin/instmodsh
lrwxrwxrwx. 1 root root 10 Apr 1 2019 /bin/ipmish -> openipmish
-rwxr-xr-x. 1 root root 68480 Apr 1 2019 /bin/jimsh
-rwxr-xr-x. 1 root root 68480 Apr 1 2019 /bin/lchsh
-rwxr-xr-x. 1 root root 3147 Apr 1 2019 /bin/lesspipe.sh
-rwxr-xr-x. 1 root root 69072 Apr 1 2019 /bin/openipmish
-r-x------. 1 root root 2235 Apr 1 2019 /bin/os_check_timezone_for_rsyslog.sh
-r-x------. 1 root root 3211 Apr 1 2019 /bin/os_rotate_and_save_log.sh
-rwxr-xr-x. 1 root root 37821 Apr 1 2019 /bin/rescan-scsi-bus.sh
-rwxr-xr-x. 1 root root 1543 Apr 1 2019 /bin/setup-nsssysinit.sh
lrwxrwxrwx. 1 root root 4 Apr 1 2019 /bin/sh -> bash
-rwxr-xr-x. 1 root root 790344 Apr 1 2019 /bin/ssh
-rwxr-xr-x. 1 root root 68632 Apr 1 2019 /bin/stapsh
lrwxrwxrwx. 1 root root 8 Apr 1 2019 /bin/tclsh -> tclsh8.6
-rwxr-xr-x. 1 root root 475064 Apr 1 2019 /bin/tcsh
-rwxr-xr-x. 1 root root 813328 Apr 1 2019 /bin/zsh
切换至sh脚本所在目录
cd $(dirname "$0")
linux bash 中暂停
read -n1 -p "Press any key to continue..."
read -p "Enter your name: " name
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5a7AZR75-1589896483574)(C:\Users\w00448203\AppData\Roaming\Typora\typora-user-images\image-20200519115645294.png)]
Shell printf 命令
另一个用于输出的命令是printf,下面的脚本中使用了printf的一些基本功能:
#!/bin/bash
#Filename: printf.sh
printf "%-5s %-10s %-4s\n" No Name Mark
printf "%-5s %-10s %-4.2f\n" 1 Sarath 80.3456
printf "%-5s %-10s %-4.2f\n" 2 James 98.9989
printf "%-5s %-10s %-4.2f\n" 3 Jeff 77.564
dash(即-)表示输出左对齐,如果不加-,表示输出右对齐。 dot 2(即.2)running off,精确到2位小数 slash n(即\n)换行符
Shell 传递参数 $
shell参数
变量 描述
$0 当前脚本的名字
$n 传递给脚本或者函数的参数,n是几,代表第几个参数
$# 输入参数的个数
$* 输入的所有参数的列表,使用双引号括起来时,所有参数当做一个整体
$@ 输入的所有参数,使用双引号时,每个参数一个个体
$? 上一个命令的执行结果,正确时返回0,不正确时返回非0
$$ 当前进程的pid
Linux Shell——流程控制
Shell表达式
-b file file 存在并且是一个块(设备)文件。
-c file file 存在并且是一个字符(设备)文件。
-d file file 存在并且是一个目录。
-e file file 存在。
-f file file 存在并且是一个普通文件。
Shell脚本调试选项
sh -x task.sh
Shell本身提供一些调试方法选项:
- -n,读一遍脚本中的命令但不执行,用于检查脚本中的语法错误。
- -v,一边执行脚本,一边将执行过的脚本命令打印到标准输出。
- -x,提供跟踪执行信息,将执行的每一条命令和结果依次打印出来。
使用这些选项有三种方法(注意:避免几种调试选项混用)
- 1.在命令行提供参数:
$sh -x script.sh
- 2.脚本开头提供参数:
#!/bin/sh -x
- 3.在脚本中用set命令启用or禁用参数:其中
set -x
表示启用,set +x
表示禁用。
Shell文件包含,跨文件调用函数、变量
Shell参考资料
-
Advanced Bash-Scripting Guide,非常详细,非常易读,大量example,既可以当入门教材,也可以当做工具书查阅