[Shell习题] 常见题系列一

1 如何向脚本传递参数 ?

./script argument
例子: 显示脚本文件名称

./show.sh file1.txt    #file1.txt为输入参数
cat show.sh
#!/bin/bash
echo $1

2 如何在脚本中使用参数 ?

第一个参数 : $1,第二个参数 :$2
例子 : 脚本会复制文件(arg1) 到目标地址(arg2)

./copy.sh file1.txt /home/username/tmp
cat copy.sh
#!/bin/bash
cp $1 $2

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

$#

4 如何在脚本中获取脚本名称 ?

$0

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

$?

实例

$ cat test.sh
#!/bin/sh
echo "this is $1"
echo "that is $2"
echo "there are $# thing"
echo "file name is $0"

$ ./test.sh dog cat
this is dog
that is cat
there are 2 thing
file name is ./test.sh

6 如何获取文件的最后一行 ?

tail-1 filename

7 如何获取文件的第一行 ?

head-1 filename

$ tail -1 test.sh
echo "file name is $0"
$ head -1 test.sh
#!/bin/sh

8 如何获取一个文件每一行的第二个元素 ?

awk '{print $2}'

$ awk '{print $2}' test.sh
is
is
are
name
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值