我可以在 bash 的文件路径中使用变量吗?如果是这样,如何?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35566239/
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
Can I use a variable in a file path in bash? If so, how?
提问by TheVideotapes
I'm trying to write a small shell script to find the most recently-added file in a directory and then move that file elsewhere. If I use:
我正在尝试编写一个小的 shell 脚本来查找目录中最近添加的文件,然后将该文件移动到其他地方。如果我使用:
ls -t ~/directory | head -1
and then store this in the variable VARIABLE_NAME, why can't I then then move this to ~/otherdirectory via:
然后将其存储在变量 VARIABLE_NAME 中,为什么我不能然后通过以下方式将其移动到 ~/otherdirectory :
mv ~/directory/$VARIABLE_NAME ~/otherdirectory
I've searched around here and Googled, but there doesn't seem to be any information on using variables in file paths? Is there a better way to do this?
我已经在这里搜索并谷歌搜索,但似乎没有关于在文件路径中使用变量的任何信息?有一个更好的方法吗?
Edit: Here's the portion of the script:
编辑:这是脚本的一部分:
ls -t ~/downloads | head -1
read diags
mv ~/downloads/$diags ~/desktop/testfolder
回答by assefamaru
You can do the following in your script:
您可以在脚本中执行以下操作:
diags=$(ls -t ~/downloads | head -1)
mv ~/downloads/"$diags" ~/desktop/testfolder
In this case, diags
is assigned the value of ls -t ~/downloads | head -1
, which can be called on by mv
.
在这种情况下,diags
被分配了 的值ls -t ~/downloads | head -1
,该值可由 调用mv
。
回答by Dirk Herrmann
The following commands
以下命令
ls -t ~/downloads | head -1
read diags
are probably not what you intend: the read command does not receive its input from the command before. Instead, it waits for input from stdin, which is why you believe the script to 'hang'. Maybe you wanted to do the following (at least this was my first erroneous attempt at providing a better solution):
可能不是您想要的:读取命令之前没有从命令接收其输入。相反,它等待来自 stdin 的输入,这就是您认为脚本“挂起”的原因。也许您想执行以下操作(至少这是我第一次错误地尝试提供更好的解决方案):
ls -t ~/downloads | head -1 | read diags
However, this will (as mentioned by alvits) also not work, because each element of the pipe runs as a separate command: The variable diags therefore is not part of the parent shell, but of a subprocess.
但是,这(正如 alvits 提到的)也不起作用,因为管道的每个元素都作为单独的命令运行:因此变量 diags 不是父 shell 的一部分,而是子进程的一部分。
The proper solution therefore is:
因此,正确的解决方案是:
diags=$(ls -t ~/downloads | head -1)
There are, however, further possible problems, which would make the subsequent mv command fail:
然而,还有更多可能的问题,这会使后续的 mv 命令失败:
- The directory might be empty.
- The file name might contain spaces, newlines etc.
- 该目录可能为空。
- 文件名可能包含空格、换行符等。