Bash-将变量连接到路径 [英] Bash - Concatenating Variable on to Path

查看:150
本文介绍了Bash-将变量连接到路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个bash脚本,它将在我的根目录中解压缩文件:

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

推荐答案

在变量中时,波浪号扩展不起作用.您可以改用$HOME变量:

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"

这篇关于Bash-将变量连接到路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆