How to pass a terminal command as an argument to another command
Solution 1
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)
Solution 2
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
Related videos on Youtube
Andrew Hoos
Updated on September 18, 2022Comments
-
Andrew Hoos over 1 year
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.
-
Scott - Слава Україні almost 11 years
-
-
Admin almost 11 years@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.
-
brevno almost 11 yearsFWIW, 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.