bash:将字符串变量解释为文件名/路径

Kei*_*ley 19 string bash filenames

我的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
Run Code Online (Sandbox Code Playgroud)

得到:

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
Run Code Online (Sandbox Code Playgroud)

如上所述,我无法将命令行参数传递给上面的例程,因为我得到了与引用的字符串相同的行为.

mic*_*ica 36

这是 - ~扩展规则的一部分.在Bash手册中明确指出,当~引用时不执行此扩展.

解决方法1

不引用~.

file=~/path/to/file
Run Code Online (Sandbox Code Playgroud)

如果您需要引用文件名的其余部分:

file=~/"path with spaces/to/file"
Run Code Online (Sandbox Code Playgroud)

(这在花园品种的外壳中完全合法.)

解决方法2

$HOME而不是~.

file="$HOME/path/to/file"
Run Code Online (Sandbox Code Playgroud)

BTW:Shell变量类型

你似乎对shell变量的类型有点困惑.

一切都是一个字符串.

重复直到它沉入:一切都是一个字符串.(除了整数,但它们主要是在字符串AFAIK之上的黑客.和数组,但它们是字符串数组.)

这是一个shell字符串:"foo".也是"42".也是42.也是foo.如果你不需要引用东西,那就不合理了; 谁想打字"ls" "-la" "some/dir"

  • `file=~"/带空格的路径/to/file"` 也不起作用。需要写`file=~/"带空格的路径/to/file"` (2认同)