【shell脚本】基本脚本

1 命令行界面使用多个命令

中间用分号隔开

ls;ll;ll -a

2 创建脚本文件

$vim a.sh
#!/bin/bash
ls;ls -a

#!/bin/bash 使用GUN bash shell

执行脚本

$a.sh
-bash: a.sh: command not found

要使用绝对路径

$./a.sh
-bash: ./a.sh: Permission denied

无执行权限,默认umask是664权限,给执行权限

$chmod u+x  a.sh
$./a.sh 
a.sh  a.txt  nginx.log	tail  tesh.sh  test  testdir  test.sh
.  ..  a.sh  a.txt  .bash_history  .bash_logout  .bash_profile	.bashrc  .lesshst  nginx.log  .pki  tail  tesh.sh  .tesh.sh.swp  test  testdir	test.sh  .viminfo

3 echo命令进行显示

$cat a.sh 
#!/bin/bash
echo  show list:  
ls
echo show list  and  show all file:
ls -a

运行:

$./a.sh
show list:
a.sh  a.txt  nginx.log	tail  tesh.sh  test  testdir  test.sh
show list and show all file:
.  ..  a.sh  a.txt  .bash_history  .bash_logout  .bash_profile	.bashrc  .lesshst  nginx.log  .pki  tail  tesh.sh  .tesh.sh.swp  test  testdir	test.sh  .viminfo

使得文本字符串和命令行的输出 在同一行,使用-n命令

$cat a.sh 
#!/bin/bash
echo -n "show list: "
ls
echo show list  and  show all file:
ls -a

运行:

$./a.sh 
show list: a.sh  a.txt  nginx.log	tail  tesh.sh  test  testdir  test.sh
show list and show all file:
.  ..  a.sh  a.txt  .bash_history  .bash_logout  .bash_profile	.bashrc  .lesshst  nginx.log  .pki  tail  tesh.sh  .tesh.sh.swp  test  testdir	test.sh  .viminfo

4 使用变量

4.1 环境变量

set命令获取当前环境变量列表
SSH_TTY=/dev/pts/2
TERM=xterm
UID=2642
USER=50485581
XDG_RUNTIME_DIR=/run/user/2642
XDG_SESSION_ID=1480097

输出环境变量用 $符号:
echo $UID

4.2 用户变量

  • 字母、数字、下划线组成
  • 长度不超过20个字符
  • 区分大小写
  • 变量 等于 值之前不用空格
  • 引用变量用$
$a=10
$echo $a
10

4.3 命令的输出赋给变量

用反引号命令() 或者使用$()命令

$test=`date`
$echo $test
Tue Apr 28 15:25:39 CST 2020
$test=$(date)
$echo $test
Tue Apr 28 15:27:08 CST 2020

使用命令替换在获取当前日期,并用它来生成唯一的文件名

$test=`date +%y%m%d`
[50485581@shell.testing-studio.com ~]$echo $test
200428
$ls > log.$test
$ls
 log.200428  

5 重定向输入和输出

5.1 输出重定向

将命令的输出 发送到文件中 使用>

$date > log
$cat log
Tue Apr 28 15:47:49 CST 2020

若文件存在则内容会覆盖,若不想覆盖用最追加 >>
$date >> log

5.2 输入重定向

将文件的内容输入到命令 使用<

$wc -l < a.sh
5

6 管道命令

将一个命令的输出作为另一个命令的输入,通过|
command1 | command2

7 执行数学运算

7.1 expr命令

$a=10
$b=20
$echo `expr  $a + $b`
30
$echo `expr  $a - $b`
-10
$echo `expr  $a \* $b`
200
$echo `expr  $a / $b`
0

注意: *需要转义

7.2 方括号

将数学表达式表达使用 $[operation]

$var1=$[1 + 5]
$echo $var1
6

注意:用方括号比较适用于shell脚本

7.3 浮点解决方案

1、bc基本用法
linux下的计算器是bc ,退出同quit
2、在脚本中使用bc

8 退出脚本

查看退出码:
echo $?
正确的命令退出码是0

退出:
exit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值