-1

I want to run this command:

ls -arth Test*log | tail -1

... and pass its output as an argument to:

open /Applications/Utilities/Console.app <previous output>

I would like to do this all in one line.

1

2 Answers 2

4

This is known as command substitution:

open /Applications/Utilities/Console.app "$(ls -arth Test*log | tail -1)"

If you're certain that the output of the command you're substituting won't contain spaces or newlines (or if you want to supply space/newline-separated output as multiple arguments), you can omit the quotes:

open /Applications/Utilities/Console.app $(ls -arth Test*log | tail -1)
2
  • @Lauri Ranta please don't change code in an answer. It's especially confusing when your change alters something which had been deliberately kept the same as in the question for demonstration purposes.
    – user173718
    Aug 2, 2013 at 22:58
  • FWIW, I suggested changing the first command to open -a Console "$(ls -t Test*log | head -n1)". open /Applications/Utilities/Console.app "$(ls -arth Test*log | tail -1)" opens Console.app and the file in the default application. The number-only options for head and tail have been deprecated by POSIX.
    – Lri
    Aug 2, 2013 at 23:16
1

This is simple enough

open /Applications/Utilities/Console.app `ls -arth Test*log | tail -1`

Any command included between grave accents will execute in new bash environment, exit upon execution and substitute itself with its result

If I execute a simple "ls" command with grave accents around it in my home folder I get such an error:

john@ship:~$ `ls`
Desktop: command not found

Which means that bash tries to execute return value until the proper delimiter as a command

Here's one more example to clarify this hacky technique:

john@ship:~$ `echo "ls -l"`
total 36
drwxr-xr-x 2 john john 4096 Jul 27 19:43 Desktop
drwxr-xr-x 2 john john 4096 Jul 27 19:43 Documents
drwxr-xr-x 2 john john 4096 Aug  2 22:04 Downloads
drwxr-xr-x 7 john john 4096 Aug  2 19:28 Music
drwxr-xr-x 2 john john 4096 Aug  2 10:49 Pictures
drwxrwxr-x 3 john john 4096 Jul 28 22:21 Projects
drwxr-xr-x 2 john john 4096 Jul 27 19:43 Public
drwxr-xr-x 2 john john 4096 Jul 27 19:43 Templates
drwxr-xr-x 2 john john 4096 Jul 27 19:43 Videos

You must log in to answer this question.

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