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