0

I dont understand what does this programme does :

if command -v apt-get > /dev/null; then
dpkg-query -W -f='...'

i dont understand how the command : "command" works

akmot
  • 63
  • 8

2 Answers2

1

There are different ways to do things in the shell.

  1. The default is to execute shell builtins.

  2. Next commands (binaries, scripts, etc; basically something external to the shell) are looked up in the directories listed in the PATH variable.

  3. This is followed by aliases. These are reusable abbreviations to commands, you can think of them as a way to save typing. They are usually defined in the shell's rc files. For example I have this defined in my ~/.bashrc: alias lt='ls --color=tty -lhtr'; it lets me type only lt to get a reverse sorted list of files (newest at the bottom).

  4. More complex commands can be grouped into shell functions.

The command command is a shell builtin that allows you to bypass any functions that might also match a binary in your PATH, or any aliases. Say I use rsync frequently between specific hosts, so I wrote a function called rsync that includes the destination with all the options, allowing me to type less. However if I want to run rsync with a different destination, I could use command rsync <other rsync options> to bypass the function definition. Note that aliases are not bypassed; this is relevant if you are using command interactively. You can find the documentation in the builtin page linked above, or by typing help command

suvayu
  • 4,271
  • 2
  • 29
  • 35
0

See man bash or help command in bash for help:

Runs COMMAND with ARGS suppressing shell function lookup, ...

The if checks whether there is a command apt-get; if there is a function apt-get, it's ignored.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • And, I think, if there is an alias, it is ignored as well. At least the man-page says: **Only** builtin commands or commands found in the PATH are executed. – user1934428 Mar 21 '22 at 10:16
  • From my testing it seems `command -v` doesn't ignore aliases, but in a script it's probably irrelevant, as non-interactive scripts usually don't `shopt -s expand_aliases`. – choroba Mar 21 '22 at 10:22
  • The `-v` does not make sense for such a test. I just tested: `command xxx` (without -v), and this indeed ignores an alias named `xxx` (bash version 4.4.12). I think it is worth mentioning aliases, because I found from discussions here that people for some reason seem to like them, and we don't know whether the OP is in an interactive context (the code displayed could be part of an interactively used shell function), or is non-interactive, but has alias expansion turned on. – user1934428 Mar 21 '22 at 10:26
  • The code in the question has `command -v`. – choroba Mar 21 '22 at 10:46
  • Indeed! Thanks for pointing this out. – user1934428 Mar 21 '22 at 16:02