如果需要给命令或者我们的shell script. 传递参数,我们可以使用shell script. 默认的变量($0,$1...)
[linux@zeng bin]$ cat argument.sh
#!/bin/bash
#
#This shell script. about command line arguments.
#
echo "Total number of command line arguments are $#"
echo "Your shell script. name is $0"
echo "First argument is $1"
echo "Second argument si $2"
cp $1 $2
echo "All argument are:$* or $@"
[linux@zeng bin]$ argument.sh /etc/inittab /home/linux/bin
Total number of command line arguments are 2
Your shell script. name is /home/linux/bin/argument.sh
First argument is /etc/inittab
Second argument si /home/linux/bin
All argument are:/etc/inittab /home/linux/bin or /etc/inittab /home/linux/bin
刚才运行脚本的时候复制过来的文件。
[linux@zeng bin]$ ll inittab
-rw-r--r--. 1 linux linux 926 Apr 5 20:08 inittab
注:
$# 表示参数的个数,这里是2.
$0 表示运行命令(程序)的名称,这里是 /home/linux/bin/argument.sh
$1 表示由命令行提供的第一个参数。
$2表示由命令行提供的第二个参数。
$N 表示由命令行提高的第N个参数。
$@与$* 表示所有的命令行参数。
数据流重定向与管道命令
在linux 中数据流分为三类:
1、标准输入(stdin),文件描述符0,使用< 或 <<.
2、标准输出(stdout), 文件描述符 1,使用> 或 >>.
3、标准错误输出(stderr), 文件描述符 2,使用 2> 或2>>.
示例:
把 ll 的输出重定向到 list.txt 文件。在这里list.txt 文件将会被自动的创建,如果该文件已经存在其中的内容会被覆盖掉。
[oracle@zeng ~]$ ll > list.txt
使用mail.txt 文件中的内容作为输入。
[oracle@zeng ~]$ mail root < mail.txt
往 ~/.bash_profile 文件中添加一行。
[oracle@zeng ~]$ echo "HISTSIZE=100" >> ~/.bash_profile
使用输出重定向把标准输出和标准错误输出分开来。
[oracle@zeng ~]$ find /home -name .bash_profile
find: `/home/linux': Permission denied
find: `/home/hello': Permission denied
/home/oracle/.bash_profile
[oracle@zeng ~]$ find /home -name .bash_profile >right.txt 2>error.txt
[oracle@zeng ~]$ cat right.txt
/home/oracle/.bash_profile
[oracle@zeng ~]$ cat error.txt
find: `/home/linux': Permission denied
find: `/home/hello': Permission denied
如果标准错误输出我们不想保存的话,可以将他从定位到 /dev/null(bit bucket,垃圾黑桶)。
[oracle@zeng ~]$ find /home -name .bash_profile >>right.txt 2>/dev/null
使用的是>>,所以append find 的输出。
[oracle@zeng ~]$ cat right.txt
/home/oracle/.bash_profile
/home/oracle/.bash_profile
标准输出重定向是不会重定向标准错误输出的。
[oracle@zeng ~]$ find /home -name .bash_profile >right.txt
find: `/home/linux': Permission denied
find: `/home/hello': Permission denied
可以使用&> right.txt 或者使用> right.txt 2>&1来把标准输出与标准错误输出重定向到同一个文件中。
[oracle@zeng ~]$ find /home -name .bash_profile &>right.txt
[oracle@zeng ~]$ cat right.txt
find: `/home/linux': Permission denied
find: `/home/hello': Permission denied
/home/oracle/.bash_profile
管道命令(pipe):就是把一个程序的输出作为另外一个程序的输入。语法格式如下:
命令1的标准输出作为命令2的标准输入:command1 | command2
命令1 的标准输出与标准错误输出作为命令2的标准输入:command1 2>&1 | command2