4

Currently, I have a bash script that will untar a file in my root directory:

#!/bin/bash
tar xvf ~/some-file.tar

This works without problems. Now, I would like to change this so I can specify the path to the file in a pre-defined variable like such:

#!/bin/bash
p="~"
tar xvf $p/some-file.tar

This gives me the following error message:

tar: ~/some-file.tar: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now

The path to the file seems to be correct, however, are there some hidden characters causing this to fail? What is the proper way to concatenate a variable and a path without storing both in string variables (if there is one)?

4
  • This was simply an example, the reason I would like to store the path in a variable is because it may change based on how the script is run Commented Jul 14, 2015 at 16:45
  • 1
    But the tilde is the root of the problem... Commented Jul 14, 2015 at 16:56
  • Yes, I did not realize this when I posted Commented Jul 14, 2015 at 17:23
  • Always test the simplest thing ;) stackoverflow.com/help/mcve Commented Jul 14, 2015 at 17:42

1 Answer 1

6

Tilde expansion doesn't work when inside a variable. You can use the $HOME variable instead:

#!/bin/bash
p=$HOME
tar xvf "$p/some_file.tar"
Sign up to request clarification or add additional context in comments.

5 Comments

Ah, I see. I did not realize that the error was due to the tilde. Thanks!
One question however: I plan to take the path as a command line option in my script. How do I handle the ~ if the user decides to enter it?
just a side note: ~ only works when it's the first char of the argument with no quote. for example, echo abc=~ will print literally.
@kshah You don't need to handle it. It will be interpreted by the shell when the user types it in his terminal.
@kshah it's better for you to delegate to other tool to make your life easier, like python, have a look at os.path.expanduser. too naive solution won't work, for example, tilde expansion support user name suffix: ~user1 should expand to home folder of user1.

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.