31.9 Shell Command Guessing

Based upon the name of a file, Dired tries to guess what shell command you might want to apply to it. For example, if you have point on a file named foo.tar and you press !, Dired will guess that you want to run ‘tar xvf’, and suggest that as the default shell command.

You can type M-n to get the default into the minibuffer for editing. If there are several commands for a given file, type M-n several times to see each matching command in order.

Dired only tries to guess a command for a single file, never for a list of marked files.

Variable: dired-guess-shell-alist-default

This variable specifies the predefined rules for guessing shell commands suitable for certain files. Set this to nil to turn guessing off. The elements of dired-guess-shell-alist-user (defined by the user) will override these rules.

Variable: dired-guess-shell-alist-user

If non-nil, this variable specifies the user-defined alist of file regexps and their suggested commands. These rules take precedence over the predefined rules in the variable dired-guess-shell-alist-default when dired-do-shell-command is run). The default is nil.

Each element of the alist looks like

(regexp command…)

where each command can either be a string or a Lisp expression that evaluates to a string. If several commands are given, all of them will temporarily be pushed onto the history.

A ‘*’ in the shell command stands for the file name that matched regexp. When Emacs invokes the command, it replaces each instance of ‘*’ with the matched file name.

To add rules for ‘.foo’ and ‘.bar’ file extensions, add this to your Init file:

(setq dired-guess-shell-alist-user
       (list "\\.foo$" "foo-command")  ; fixed rule
       ;; possibly more rules...
       (list "\\.bar$"  ; rule with condition test
             '(if condition

This will override any predefined rules for the same extensions.

You can find more user options with M-x customize-group RET dired-guess RET.