bash 将文件名保存为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8981115/
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
Saving a file name as a variable
提问by user1161080
I need a way to save the name of a file into a variable, so that after I delete that file, I can create a new file with the same name as the original. How can I do that?
我需要一种将文件名保存到变量中的方法,以便在删除该文件后,我可以创建一个与原始文件同名的新文件。我怎样才能做到这一点?
for example, I take in a file and store it as var1 and another as var2 using
例如,我使用一个文件并将其存储为 var1 和另一个存储为 var2
file=$var1
file=$var2
later in my code, I need to delete var2 and create a link to var1 with the same name as the original var2. The command:
稍后在我的代码中,我需要删除 var2 并创建一个与原始 var2 同名的 var1 链接。命令:
rm var2
ln var1 var2
creates an error message I think I need to create a temporary variable that holds just the name of the file var2, but I'm not sure how to do that. Any ideas? Thanks!
创建一条错误消息 我想我需要创建一个仅包含文件 var2 名称的临时变量,但我不知道该怎么做。有任何想法吗?谢谢!
回答by paulsm4
I think you just need a "$" sign:
我认为你只需要一个“$”符号:
# Set a variable
myvar=moose
# Get the contents of a variable
echo $myvar # Prints "moose"
In your case:
在你的情况下:
var1=myfirstfile
var2=mysecondfile
rm $var2
ln $var1 $var2
回答by Igor Hatarist
Which shell are you using? What OS?
你用的是哪个壳?什么操作系统?
With Linux and BASH it would be:
对于 Linux 和 BASH,它将是:
#!/bin/bash
# Set variable $var1, it will contain a string - 'file':
var1='file'
# Set variable $var2, it will contain a string - 'another_file':
var2='another_file'
# Run 'rm' command with an argument - a variable $var1
# So it's like running a command "rm file"
rm $var1
# Run 'ln' command with $var1 and $var2 as arguments
# So it's like running a command "ln file another_file"
ln $var1 $var2
But in Mac OS X lnhas different syntax and you have to switch arguments in ln:
但是在 Mac OS X 中ln有不同的语法,你必须在 中切换参数ln:
ln $var2 $var1
Edit:Also, your problem may be that you use file path with spaces in it, so bash shows "no such file or directory"errors.
It can't find the file because of rm's syntax. For example:
编辑:另外,您的问题可能是您使用的文件路径中包含空格,因此 bash 显示"no such file or directory"错误。由于rm的语法,它找不到文件。例如:
var1='long named file'
rm $var1
This script does run a command "rm long named file", which, in turn, deletes three files - long, namedand file.
Then that would do the thing for you:
这个脚本里运行一个命令"rm long named file",这反过来,删除三个文件- long,named和file。那么这将为你做这件事:
rm "$var1"
ln "$var1" "$var2"

