2

Adding in comments to ask specific questions as I go:

Single or double quote marks when settings strings?

echo "Starting..."

Do I need to terminate the line with a ;?

TARGET_DIR="~/Downloads"

I can't get the $TARGET_DIR to expand, tried quotes, preens with $etc, is there a canonical beginners guide to these types of issues that presents them in the proper way, not the force it to work with back tics and multiple lines?

LAST_DOWNLOADED_FILE=$(ls -t $TARGET_DIR | head -n1)
echo "Your newest file in $TARGET_DIR is: $LAST_DOWNLOADED_FILE"

When run on Mac, I get:

ls: ~/Downloads: No such file or directory
Your newest file in ~/Downloads is:

Trying as a one liner:

me@compy $FOO="~/Downloads"; echo $(FOO); ls -t $FOO | head -n1
-bash: FOO: command not found
1

2 Answers 2

4

You need:

TARGET_DIR=~/Downloads

i.e. keep tilde ~/ outside quote, otherwise shell won't expand it and ~ will be treated literally.

Sign up to request clarification or add additional context in comments.

5 Comments

+1. Note that TARGET_DIR=~/"Downloads" and TARGET_DIR=~/'Downloads' also work. (Not needed for this example, but useful if the stuff after the ~/ is more complicated.)
No, the whole ~/ part needs to be outside the quotes.
Yes I misspoke, you're right it should be ~/ outside quotes.
Thanks! What is the proper way to deal with variables that have spaces in their names, or may: echo "Your newest file in $SOME_FILE"; say that $SOME_FILE is 'this is a test'
@Scott: You can do TARGETDIR=~/"$SOME_FILE"
0

~ sign inside quotes is considered a literal by shell. You need to either keep it outside of quotes as anubhava suggested in his answer or use eval to interpolate it.

$ TARGET_DIR="~/tmp"
$ echo $TARGET_DIR
~/tmp
$ eval echo $TARGET_DIR
/home/jaypalsingh/tmp

Note: Make sure you read all the pros and cons of eval before considering it as an option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.