Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the result of a command as an argument in bash?

To create a playlist for all of the music in a folder, I am using the following command in bash:

ls > list.txt 

I would like to use the result of the pwd command for the name of the playlist.

Something like:

ls > ${pwd}.txt 

That doesn't work though - can anyone tell me what syntax I need to use to do something like this?

Edit: As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!

like image 859
HoboBen Avatar asked Sep 12 '08 02:09

HoboBen


People also ask

How do you echo the output of a command?

The echo command writes text to standard output (stdout). The syntax of using the echo command is pretty straightforward: echo [OPTIONS] STRING... Some common usages of the echo command are piping shell variable to other commands, writing text to stdout in a shell script, and redirecting text to a file.

How do I run a command-line argument in bash?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.

What in bash lets you take the output of a previous command and use it as input in the next command?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.


2 Answers

The best way to do this is with "$(command substitution)" (thanks, Landon):

ls > "$(pwd).txt" 

You will sometimes also see people use the older backtick notation, but this has several drawbacks in terms of nesting and escaping:

ls > "`pwd`.txt" 

Note that the unprocessed substitution of pwd is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a .txt extension. Thomas Kammeyer pointed out that the basename command strips the leading directory, so this would create a text file in the current directory with the name of that directory:

ls > "$(basename "$(pwd)").txt" 

Also thanks to erichui for bringing up the problem of spaces in the path.

like image 108
8 revs, 2 users 82% Avatar answered Oct 09 '22 11:10

8 revs, 2 users 82%


This is equivalent to the backtick solution:

ls > $(pwd).txt 
like image 22
Landon Avatar answered Oct 09 '22 12:10

Landon