Bash if将变量保存到配置文件的语句不起作用

时间:2013-05-14 00:30:23

标签: macos bash if-statement variable-assignment alias

这是我的代码:

alias radio='
if [ -e "$station" ]
then
    open $station
else
    say "I still don't know what your favorite radio station is sir. Would you mind giving me the link?"
    echo "What is the link of your favorite station?"
    read station
    echo "station="$station"" >> ~/.fis/config
    say "You can now try the command again."
fi'

代码运行到它要求链接的部分。当我提供链接时,我收到以下错误:

  

-bash:station = http://www.cidadefm.iol.pt/player/player.html?:没有这样的文件或目录

有没有人知道可能出现什么问题?

2 个答案:

答案 0 :(得分:3)

WhatsWrongWithMyScript.com有帮助地指出“不要”中的撇号正在终止单引号表达式。而不是通过使用“不要”修复此问题,请改为使用函数:

radio() {
  if [ -e "$station" ]
  then
      open $station
  else
      say "I still don't know what your favorite radio station is sir. Would you mind giving   me the link?"
      echo "What is the link of your favorite station?"
      read station
      echo "station=\"$station\"" >> ~/.fis/config
      say "You can now try the command again."
  fi
}

答案 1 :(得分:2)

主要问题是您在引号之外使用$station。可能有&分解命令。

您似乎使用“station”变量名称用于两个不同的目的。这令人困惑。

另外,将所有内容放入别名有点尴尬。我会使用一个函数

radio () {
    local file=~/.fis/config
    if [ -f "$file" ]
    then
        station=$(< "$file")
    else
        say "I still don't know what your favorite radio station is sir. Would you mind giving me the link?"
        echo "What is the URL of your favorite station?"
        read staton
        echo "$station" > "$file"
    fi    
    open "$station"
}