'What's the magic of "-" (a dash) in command-line parameters?

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?



Solution 1:[1]

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.

Solution 2:[2]

- 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.

Solution 3:[3]

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.

Solution 4:[4]

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!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ignacio Vazquez-Abrams
Solution 2
Solution 3 The Red Pea
Solution 4 William Pursell