LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   which quotes and brackets to use within a () (https://www.linuxquestions.org/questions/linux-newbie-8/which-quotes-and-brackets-to-use-within-a-4175454014/)

Batistuta_g_2000 03-14-2013 03:56 AM

which quotes and brackets to use within a ()
 
Hi,

I have a variable - lastfile which I need to set to the last modified tar file in a directory, named $PROJECTNAME.

The script below works without $PROJECTNAME just fine, but how can I include it as the filename within the ()?

lastfile=$(find . -type f -name '${PROJECTNAME}*.tar.gz' -printf '%p\n' | sort -nr | head -n 1 | sed 's/^..//')

Batistuta_g_2000 03-14-2013 04:07 AM

Quote:

Originally Posted by Batistuta_g_2000 (Post 4911277)
Hi,

I have a variable - lastfile which I need to set to the last modified tar file in a directory, named $PROJECTNAME.

The script below works without $PROJECTNAME just fine, but how can I include it as the filename within the ()?

lastfile=$(find . -type f -name '${PROJECTNAME}*.tar.gz' -printf '%p\n' | sort -nr | head -n 1 | sed 's/^..//')

Got it:

lastfile=$(find . -type f -name "$PROJECTNAME*.tar.gz" -printf '%p\n' | sort -nr | head -n 1 | sed 's/^..//')

David the H. 03-15-2013 08:21 AM

Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.

"$(..)" command substitution acts as a sub-shell. That means it's its own execution environment. Everything inside runs exactly like a command written on the main command line.

As for quoting, it's very important to understand how the shell processes them and arguments. See here:

http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes


By the way, head isn't needed if sed is also being used:

Code:

... | sort -nr | sed -n '1s/^..//p')
If you don't need recursive searching, however (or perhaps even if you do), there are safer ways to get the final file in a list, generally by using an array. It may even be as simple as this:

Code:

files=( "$PROJECTNAME"*.tar.gz )
lastfile=${files[-1]}        #or "${files[0]}" depending on which end you need to take it from.

This one relies on the shell being able to naturally sort the files. It's highly recommended to ensure that any numbers in the filenames are always zero-padded, and that any dates in them use the proper, standardized ISO 8601 format, to allow the shell to automatically sort them for you. Otherwise you're back to using sort or some other technique.


How can I find the latest (newest, earliest, oldest) file in a directory?
http://mywiki.wooledge.org/BashFAQ/003

How can I get the newest (or oldest) file from a directory?
http://mywiki.wooledge.org/BashFAQ/099


All times are GMT -5. The time now is 01:56 PM.