bash:将字符串变量解释为文件名/路径 [英] bash: interpret string variable as file name/path
问题描述
我的bash脚本以字符串形式接收文件名(或相对路径),但是必须从该文件中读取.如果我直接在脚本中将文件名声明为文字(不带引号),则只能从文件名中读取...这对于参数来说是不可能的,因为它们是隐式的字符串开头.观察:
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:
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
收益:
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.
推荐答案
这是~
-扩展规则的一部分. Bash手册中明确指出,~
用引号引起来时,不会执行此扩展.
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.
不要引用~
.
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.)
使用$HOME
代替~
.
file="$HOME/path/to/file"
BTW:Shell变量类型
您似乎对shell变量的类型有些困惑.
BTW: Shell variable types
You seem to be a little confused about the types of shell variables.
一切都是字符串.
重复直到它陷入:一切都是字符串.(除了整数,但它们大多是在字符串AFAIK之上的hack.和数组,但它们是字符串的数组.)
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.)
这是一个外壳程序字符串:"foo"
. "42"
也是如此. 42
也是如此. foo
也是如此.如果您不需要引用任何内容,则最好不要引用.谁想输入"ls" "-la" "some/dir"
?
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"
?
这篇关于bash:将字符串变量解释为文件名/路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!