我的 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
产量:
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
如上所述,我无法将命令行参数传递给上面的例程,因为我得到的行为与引用字符串的行为相同。