简体   繁体   中英

What is the meaning of “command -v lftp >/dev/null 2>&1”?

I have a script that after a while will run this, but I don't really understand how it works. My understanding for now is that if command fails, it will echo something in stderr, but I tried

command -v lftp >/dev/null 2>&1

and it outputs nothing even if I have lftp installed. Can someone explain me what this line does exactly?

# check lftp is installed
command -v lftp >/dev/null 2>&1 || {
    echo >&2 "lftp is required. Please install it.      Aborting."
    exit 1
}

It looks for lftp on the PATH and throws away the location it finds, and/or any errors (it sends them to /dev/null , which is like a black hole - data enters it, nothing ever leaves it).

Then, if it failed to find it, it displays the error message and exits the script with an exit code of 1 .

the > /dev/null sends the standard output (file descriptor 1) of the command to the null device (this throws all the output away) then the 2>&1 attaches file descriptor 2 (standard error) to the same place as file descriptor 1 (which was the null device).

This is just a standard way of discarding all the output. The following would have the same effect:

... 2> /dev/null 1>&2

Note that order is important so:

2>&1 > /dev/null

would not have the same effect; you would discard standard out but leave standard error attached to the file descriptor of standard out.

The thing to know that helps make sense of it all is that by default in Unix a program starts up with three file descriptors open: 0 = standard in (stdin or, in C++, cin) 1 = standard out (stdout or, in C++, cout) 2 = standard error (stderr or in C++, cerr)

command -v is the POSIX-standard way to find out what the shell will do to execute a command. If the argument corresponds to a executable, it will print out the path, and exit with successful status. If the argument is nothing that the shell can execute, it will exit with failure.

Since the user is not interested in whatever command -v prints, both stdout and stderr are redirected to /dev/null , this is done by first redirecting stdout to /dev/null , and then duplicating stdout into stderr: >/dev/null 2>&1

After that, if the lookup done by command -v failed, a list (enclosed in {} ) is executed. This is done with || , which you can read as the left part succeeds OR execute the right part .

The list (which is executed if command -v fails) outputs a diagnostics message to stderr, and then exits the script with failure:

>&2 duplicates stderr into stdout, now everything you write to stdout will go to what originally was just stderr. exit 1 exits with failure status. Shells use 0 exit status for success, and not 0 for failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM