2

Is there any shortcut to execute the output of the previous command, such as executing whatever is found by the locate command?

For instance, if I run this locate command and get this output...

root@kali:~/scripts# locate nasm_shell
/usr/share/metasploit-framework/tools/nasm_shell.rb

Is there any way to execute that nasm_shell.rb command with a shortcut? Just being lazy and trying to avoid copying and pasting the full command path.

2 Answers 2

3
$(locate nasm_shell)

or

`locate nasm_shell`

You can use backticks `` or $() to execute the command in a subshell, for instance:

user@host$ which df
/bin/df
user@host$ `which df`
Filesystem          1K-blocks      Used Available Use% Mounted on
...
/dev/sda1              498532    199535    268738  43% /boot
/dev/mapper/vg-home 412718256 232104076 159626276  60% /home

If there is more than a single line of output, you'll need to use grep or some other tool to select the right output:

For instance, the following has more than the output I want, to find mkdir

user@host$ locate mkdir
/bin/mkdir
/opt/project-neon5/include/KF5/KIOCore/kio/mkdirjob.h
/usr/lib/klibc/bin/mkdir
/usr/lib/mc/fish/mkdir
/usr/share/aclocal-1.14/mkdirp.m4
/usr/share/man/man1/gvfs-mkdir.1.gz
/usr/share/man/man1/mkdir.1.gz
/usr/share/man/man2/mkdir.2.gz
/usr/share/man/man2/mkdirat.2.gz
/usr/share/zsh/functions/Completion/Unix/_mkdir
/var/lib/gems/1.9.1/doc/bundler-1.3.5/ri/Bundler/mkdir_p-c.ri

I just want mkdir that lives in /bin. Using grep to select the correct output, then adding an argument to the output of the subshell:

user@host$ $(locate mkdir | grep "^\/bin") test-directory && ls -ld test-directory
drwxrwxr-x 2 user user 4096 Nov 15 21:18 test-directory

Note the use of the alternate syntax $()

1
  • Thanks - figured I'd cover all the use cases and generalize the answer some...
    – glallen
    Commented Nov 16, 2014 at 2:28
0

This should work using eval as well as locate coupled with $() like this:

eval $(locate nasm_shell)

But the risk with using this is let’s say you have multiple files with the name nasm_shell on the system. Then that command would fail since it would attempt to try and run the full output of the locate command. But if you are 100% positive what you are looking for is in one file/script like nasm_shell.rb, then this would be fine.

1
  • 1
    The eval isn't necessary, the subshell is sufficient with bash/zsh, etc. eval is mostly for constructing commands requiring concatenation of strings stackoverflow.com/questions/11065077/…
    – glallen
    Commented Nov 16, 2014 at 2:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .