bash: interpret string variable as file name/path

后端 未结 1 1681
庸人自扰
庸人自扰 2020-12-13 07:36

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

相关标签:
1条回答
  • 2020-12-13 07:54

    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.

    Workaround 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

    Use $HOME instead of ~.

    file="$HOME/path/to/file"
    

    BTW: Shell variable types

    You seem to be a little confused about the types of shell variables.

    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.)

    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"?

    0 讨论(0)
提交回复
热议问题