Bash 脚本将文件名导出到变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7000724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:33:26  来源:igfitidea点击:

Bash Scripting Export Filename to Variable

linuxbash

提问by Daven Patel

I'm trying to set a variable to a string representing a file's location and when I try to set the variable I keep on getting a 'permission denied' error, because the bash script is trying to execute the file.

我正在尝试将变量设置为表示文件位置的字符串,当我尝试设置该变量时,我不断收到“权限被拒绝”错误,因为 bash 脚本正在尝试执行该文件。

Here is the code I'm using

这是我正在使用的代码

date= 07062011
archive_dir=~/Documents/ABC/Testing
aggregate_file= `echo ${archive_dir}"/"${date}"_Aggregated.txt"`

The error I am getting is the following:

我得到的错误如下:

./8000.2146701.sh: line 32: /home/me/Documents/ABC/Testing/20110706_Aggregated.txt: Permission denied

./8000.2146701.sh:第 32 行:/home/me/Documents/ABC/Testing/20110706_Aggregated.txt:权限被拒绝

From what I understand using the backticks should allow me to take the output of the command and put it into a variable and it doesn't seem to be working. When I just do the echo statement by itself the output is the file path.

据我所知,使用反引号应该允许我获取命令的输出并将其放入一个变量中,但它似乎不起作用。当我自己执行 echo 语句时,输出是文件路径。

Thanks.

谢谢。

回答by DigitalRoss

The direct problem is the space following:

直接的问题是下面的空间:

aggregate_file=

That is:

那是:

aggregate_file= `echo ${archive_dir}"/"${date}"_Aggregated.txt"`

would have worked by simply removing the space after the assignment operator:

只需删除赋值运算符后的空格即可:

aggregate_file=`echo ${archive_dir}"/"${date}"_Aggregated.txt"`

But really it should have just been:

但实际上它应该是:

aggregate_file="${archive_dir}/${date}_Aggregated.txt"

回答by C. Ramseyer

Don't use backticks and echo, just aggregate_file="${archive_dir}/${date}_Aggregated.txt". And no spaces, as another poster mentioned.

不要使用反引号和回声,只是aggregate_file="${archive_dir}/${date}_Aggregated.txt". 正如另一张海报所提到的,没有空格。