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

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

$(locate nasm_shell)


`locate nasm_shell`

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

user@host$ which 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

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 $()

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

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