TheVideotapes
TheVideotapes

Reputation: 403

Can I use a variable in a file path in bash? If so, how?

I'm trying to write a small shell script to find the most recently-added file in a directory and then move that file elsewhere. If I use:

ls -t ~/directory | head -1

and then store this in the variable VARIABLE_NAME, why can't I then then move this to ~/otherdirectory via:

mv ~/directory/$VARIABLE_NAME ~/otherdirectory

I've searched around here and Googled, but there doesn't seem to be any information on using variables in file paths? Is there a better way to do this?

Edit: Here's the portion of the script:

ls -t ~/downloads | head -1
read diags
mv ~/downloads/$diags ~/desktop/testfolder

Upvotes: 14

Views: 44665

Answers (2)

Dirk Herrmann
Dirk Herrmann

Reputation: 5949

The following commands

ls -t ~/downloads | head -1
read diags

are probably not what you intend: the read command does not receive its input from the command before. Instead, it waits for input from stdin, which is why you believe the script to 'hang'. Maybe you wanted to do the following (at least this was my first erroneous attempt at providing a better solution):

ls -t ~/downloads | head -1 | read diags

However, this will (as mentioned by alvits) also not work, because each element of the pipe runs as a separate command: The variable diags therefore is not part of the parent shell, but of a subprocess.

The proper solution therefore is:

diags=$(ls -t ~/downloads | head -1)

There are, however, further possible problems, which would make the subsequent mv command fail:

  • The directory might be empty.
  • The file name might contain spaces, newlines etc.

Upvotes: 0

assefamaru
assefamaru

Reputation: 2789

You can do the following in your script:

diags=$(ls -t ~/downloads | head -1)
mv ~/downloads/"$diags" ~/desktop/testfolder

In this case, diags is assigned the value of ls -t ~/downloads | head -1, which can be called on by mv.

Upvotes: 24

Related Questions