What's the magic of “-” (a dash) in command-li

2019-01-03 08:50发布

Examples:

  • Create an ISO image and burn it directly to a CD.

    mkisofs -V Photos -r /home/vivek/photos | cdrecord -v dev=/dev/dvdrw -

  • Change to the previous directory.

    cd -

  • Listen on port 12345 and untar data sent to it.

    nc -l -p 12345 | tar xvzf -

What is the purpose of the dash and how do I use it?

6条回答
在下西门庆
2楼-- · 2019-01-03 09:08

If you mean the naked - at the end of the tar command, that's common on many commands that want to use a file.

It allows you to specify standard input or output rather than an actual file name.

That's the case for your first and third example. For example, the cdrecord command is taking standard input (the ISO image stream produced by mkisofs) and writing it directly to /dev/dvdrw.

With the cd command, every time you change directory, it stores the directory you came from. If you do cd with the special - "directory name", it uses that remembered directory instead of a real one. You can easily switch between two directories quite quickly by using that.

Other commands may treat - as a different special value.

查看更多
不美不萌又怎样
3楼-- · 2019-01-03 09:13

The magic is in the convention. For millennia, people have used '-' to distinguish options from arguments, and have used '-' in a filename to mean either stdin or stdout, as appropriate. Do not underestimate the power of convention!

查看更多
Deceive 欺骗
4楼-- · 2019-01-03 09:14

It means to use the program's standard input stream.

In the case of cd, it means something different -- change to the prior working directory.

查看更多
戒情不戒烟
5楼-- · 2019-01-03 09:17

It's not magic. Some commands interpret - as the user wanting to read from stdin or write to stdout; there is nothing special about it to the shell.

查看更多
【Aperson】
6楼-- · 2019-01-03 09:22

Redirection from or to stdin or stdout.

See: http://tldp.org/LDP/abs/html/special-chars.html#DASHREF2

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-03 09:25

- means exactly what each command wants it to mean. There are several common conventions, and you've seen examples of most of them in other answers, but none of them are 100% universal.

There is nothing magic about the - character as far as the shell is concerned (except that the shell itself, and some of its built-in commands like cd and echo, use it in conventional ways). Some characters, like \, ', and ", are "magical", having special meanings wherever they appear. These are "shell metacharacters". - is not like that.

To see how a given command uses -, read the documentation for that command.

查看更多
登录 后发表回答