Bash - Concatenating Variable on to Path

2020-04-13 02:17发布

问题:

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)?

回答1:

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"


标签: linux bash