Linux 命令行参数中“-“(一个减号)的作用

Linux 命令行参数中"-"(一个减号)的作用

补充说明

减号- 代表标准输入输出的一点补充
-可称之为dashminushyphen(连字符)minus-sign(减号)

# 参考,https://tldp.org/LDP/abs/html/special-chars.html

# 减号- 代表标准输入还是标准输出,视具体命令而定
# 如果命令是往外输出的,则减号- 代表标准输出stdout
# 如果命令是等待输入的,则减号- 代表标准输入stdin 
# 以下面复制文件的列子进行讲解

# 0. 环境准备
rm -rf /tmp/dir{1,2}
mkdir /tmp/dir{1,2} && cd /tmp/dir1 && touch a.txt b.txt c.txt
## 在/tmp 下创建了2 个文件夹dir1 和dir2,并在/tmp/dir1 中创建了文件a.txt、b.txt、c.txt

# 1. 复制文件
(cd /tmp/dir1 && tar -cf - .) | (cd /tmp/dir2 && tar -xvf -)
## 将/tmp/dir1 中的文件a.txt、b.txt、c.txt 复制到/tmp/dir2 下

# 2. 过程讲解
## 1. () 代表一个子shell
## 2. tar -c 创建文件,-f 指定文件,可见这里tar 是输出,所以减号`-`代表的是`stdout`
## 3. | 管道符 
### 管道的作用就是`将stdout 的内容转到stdin`供读取,所以`管道左边的输出才会作为右边的输入`
### 但是如果管道右边的命令不需要输入,例如`echo aaa | echo`,则`stdin`的内容不会被读取
## 4. tar -x 解压文件,-f 指定文件,可见这里tar 是要输入,所以减号`-`代表的是`stdin`
## 综上所述,tar 将内容写入`-(stdout)`,管道将`stdout`复制到`stdin`,最后tar 从`-(stdin)`读取

## 英文原文如下
## 1) cd /tmp/dir1
##    Source directory, where the files to be moved are.
## 2) &&
##   "And-list": if the 'cd' operation successful,
##    then execute the next command.
## 3) tar cf - .
##    The 'c' option 'tar' archiving command creates a new archive,
##    the 'f' (file) option, followed by '-' designates the target file
##    as stdout, and do it in current directory tree ('.').
## 4) |
##    Piped to ...
## 5) ( ... )
##    a subshell
## 6) cd /tmp/dir2
##    Change to the destination directory.
## 7) &&
##   "And-list", as above
## 8) tar xpvf -
##    Unarchive ('x'), preserve ownership and file permissions ('p'),
##    and send verbose messages to stdout ('v'),
##    reading data from stdin ('f' followed by '-').
##
##    Note that 'x' is a command, and 'p', 'v', 'f' are options.

用法解释

一般常见用法

# 为应用程序指定参数
ps -aux
tar -zxf test.tar
 
# 一个减号和两个减号
## 一个减号后面跟的参数必须是单字符参数,可以多个参数写在同一个减号后面
ls -l
## 两个减号后面跟的参数必须是多字符参数
ls --help
 
# 表示上一次工作目录
cd -

# 普通用户切换到root
su -
## 相当于
su – root

代表标准输入输出

# "-" 代替标准输入stdin 或标准输出stdout,视具体命令而定

# 在输出内容添加一行
cat - file.txt <<< "line num 1"
## <<< 是heredoc,这里"-"接收<<< 的输入,以匿名文件的形式供cat 读取
## cat 将"-"代表的匿名文件和file.txt 的内容连接在一起,执行结果为
### line num 1
### file.txt 第一行内容
### file.txt 第二行内容
### ......

# 只取文件的一列并与另一文件做diff
awk '{ print $1 }' a | diff - b
## 管道"|"左边的输出就是右边的输入,这里管道左边是awk 的输出,管道右边用"-"接收
## "-"再以匿名文件的形式供diff 读取,所以,这里的"-"既有输入也有输出

参考资料

Linux:减号(-)详解
linux shell环境减号”-“的用途

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值