Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

filepath

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
like image 631
TheVideotapes Avatar asked Feb 22 '16 23:02

TheVideotapes


1 Answers

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.

like image 94
assefamaru Avatar answered Sep 23 '22 05:09

assefamaru