4

I'm writing a script that is trying to insert a directory name into a pax command and I'm not sure how to get the syntax correct. This is what I'm trying, but it seems to be treating the $DIRNAME as part of the regex string.

DIRNAME=$(tar -tvf $1  | head -1 | sed -e 's:^.* \([^/]*\)/.*$:\1:')
pax -r -f $1 -s'/$DIRNAME\/upload\///'

Thanks!

1 Answer 1

6

Try using double quotes rather than single quotes when calling pax:

DIRNAME=$(tar -tvf $1  | head -1 | sed -e 's:^.* \([^/]*\)/.*$:\1:')
pax -r -f $1 -s"/$DIRNAME\/upload\///"

In several shells (eg bash and sh), $variables only get expanded when they occur in double-quoted strings, not single-quoted strings.


E.g., the following script:

#!/bin/sh

DIRNAME=$(echo 'hello')
echo "Single quotes around regexp:"
echo 'hello world' | sed 's/$DIRNAME/hi/'

echo "Double quotes around regexp:"
echo 'hello world' | sed "s/$DIRNAME/hi/"

Generates the output:

Single quotes around regexp:
hello world
Double quotes around regexp:
hi world
Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't work. The problem is that $DIRNAME is not echoing the contents of DIRNAME, but just inserting the text string $DIRNAME itself into the regex string.
What shell is the script being run in? bash? tcsh?
Sorry, I tried it again and the error I got was with the pax command, not the $DIRNAME once I double quoted it. I'm using bash.
try leaving a space between -s and its regex arguments

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.