Bash: Confused by expanding asterisk

前端 未结 1 1025
礼貌的吻别
礼貌的吻别 2021-01-27 14:30

I have a very simple scripts called test.sh.

#!/bin/bash
echo $(cat \'./data\')

while read line
do
  data=$data\' \'$line
done < \'./data\'
echo         


        
相关标签:
1条回答
  • 2021-01-27 14:58

    Rule #1, quote your variables!

    echo "$(cat data)"
    

    and

    data="$data $line"
    

    and

    echo "$data"
    

    Although as gniourf_gniourf pointed out in the comments below (since removed), the second of the three changes is actually unnecessary, as glob expansion does not occur during variable assignment.

    That said, if you just want to print the contents of the file, there's no need to use a command substitution or read loop at all. Why not just use cat data?

    Alternatively, to store the contents of the file to a variable, just use data="$(cat data)" (the quotes are important here), or as suggested in the comments above by gniourf_gniourf, data="$(< data)".

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