string bash:将字符串变量解释为文件名/路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16703624/
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
bash: interpret string variable as file name/path
提问by Keith Wiley
My bash script receives a filename (or relative path) as a string, but must then read from that file. I can only read from a filename if I declare it as a literal directly in the script (without quotes)...which is impossible for arguments since they are implicitly strings to begin with. Observe:
我的 bash 脚本以字符串形式接收文件名(或相对路径),但必须从该文件中读取。如果我直接在脚本中将其声明为文字(不带引号),我只能从文件名中读取……这对于参数来说是不可能的,因为它们是隐式字符串开头。观察:
a="~/test.txt"
#Look for it
if [[ -a $a ]] ; then
echo "A Found it"
else
echo "A Error"
fi
#Try to use it
while read line; do
echo $line
done < $a
b='~/test.txt'
#Look for it
if [[ -a $b ]] ; then
echo "B Found it"
else
echo "B Error"
fi
#Try to use it
while read line; do
echo $line
done < $b
c=~/test.txt
#Look for it
if [[ -a $c ]] ; then
echo "C Found it"
else
echo "C Error"
fi
#Try to use it
while read line; do
echo $line
done < $c
YIELDS:
产量:
A Error
./test.sh: line 10: ~/test.txt: No such file or directory
B Error
./test: line 12: ~/test.txt: No such file or directory
C Found it
Hello
As stated above, I can't pass a command line argument to the routines above since I get the same behavior that I get on the quoted strings.
如上所述,我无法将命令行参数传递给上述例程,因为我得到的行为与我在引用字符串上得到的行为相同。
回答by michaelb958--GoFundMonica
This is part of the rules of ~
-expansion. It is clearly stated in the Bash manual that this expansion is not performed when the ~
is quoted.
这是~
-expansion规则的一部分。Bash 手册中明确指出,~
引用时不执行此扩展。
Workaround 1
解决方法 1
Don't quote the ~
.
不要引用~
.
file=~/path/to/file
If you need to quote the rest of the filename:
如果您需要引用文件名的其余部分:
file=~/"path with spaces/to/file"
(This is perfectly legal in a garden-variety shell.)
(这在花园式贝壳中是完全合法的。)
Workaround 2
解决方法 2
Use $HOME
instead of ~
.
使用$HOME
代替~
。
file="$HOME/path/to/file"
BTW: Shell variable types
顺便说一句:外壳变量类型
You seem to be a little confused about the types of shell variables.
你似乎对 shell 变量的类型有点困惑。
Everything is a string.
一切都是一个字符串。
Repeat until it sinks in: Everything is a string.(Except integers, but they're mostly hacks on top of strings AFAIK. And arrays, but they're arrays of strings.)
重复直到它沉入水中:一切都是字符串。(除了整数,但它们主要是在字符串 AFAIK 之上的 hack。和数组,但它们是字符串数组。)
This is a shell string: "foo"
. So is "42"
. So is 42
. So is foo
. If you don't need to quote things, it's reasonable not to; who wants to type "ls" "-la" "some/dir"
?
这是一个 shell 字符串:"foo"
. 也是"42"
。也是42
。也是foo
。如果你不需要引用东西,不引用是合理的;谁想打字"ls" "-la" "some/dir"
?