25

I've searched everywhere. Tried echo and print. Tried single and double quotes. But I have parsed data and assigned it to a variable and would like to then evaluate it for if there is a variable within it. I will then replace the variable with a wildcard and search for the file.

Example:

var="file.$DATE.txt"

### Where it goes wrong-  Needs to identify that $DATE is within the $var varaible.
test=$(echo "$var"|grep '\$')
if [[ $test ]]
then
    ### I would use whatever fix is discovered here as well
    test=$(echo $test|sed 's/\$[a-zA-Z]*/\*/')
fi

### (Actually pulling from remote machine to local)
cat $test > /tmp/temporary.file

Here is at least one of my many failures:

PROMPT> file=blah.$DATE
PROMPT> test=$(echo "$file"|grep '\$')
PROMPT> echo $test
PROMPT>
PROMPT>

I know it has something to do with expansion, but have no idea how to work it out. Any help would be appreciated. Thanks!

3
  • What is it that you need solved? That var contain an un-expanded $date?. For that use: var='file.$DATE.txt'. To expand date when var is used? I am sure that you need to explain what you are asking. Commented Jan 28, 2016 at 18:54
  • Sorry, to test if a variable is defined within the "var" variable. Nested of sorts. Commented Jan 28, 2016 at 19:06
  • I found a way around my dilemma by immediately removing anything that appears to be a variable (without caring first that I need to) and swapping it with a wildcard: sed 's/\${*[a-zA-Z0-9_%]*}*/\*/' Commented Jan 28, 2016 at 19:08

2 Answers 2

28

If you need $date inside the variable var:

var='file.$date.txt'

That will keep the $ inside the variable:

$ echo "$var" | grep '\$'
file.$date.txt
18

Use single quotes around variables to prevent shell expansion. Example echo '$file' will not expand $file.

Edit after comment below:

You can escape the $ sign int the var variable with var="file.\$DATE.txt".

4
  • 2
    I need it to expand, but only one level. Forgot to add a step-by-step desired result. But I would like the contents of $file to be evaluated for a dollar sign ($DATE). Commented Jan 28, 2016 at 18:16
  • Edited to solve that. Commented Jan 28, 2016 at 18:24
  • I receive that data from an outside source. Even to replace the $ with a \$, I think, would require an echo. HOWEVER, let me see if when I am parsing it I can squeeze it in. Commented Jan 28, 2016 at 18:29
  • Will work for this case/example too: echo "/cpt_backup_a_\`date +\%Y_\%m_\%d\`.log". (see "`"). Commented Feb 28, 2021 at 20:02

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.