Bash从变量读取行

时间:2016-06-05 04:08:43

标签: mysql bash

嗨&提前谢谢。

我正在尝试从Bash脚本更新MySQL表上的列(版本)。

我已经使用版本号填充了一个变量,但是在列表中应用第一个版本后它失败了。

CODE:

UP_VER=`seq ${DB_VER} ${LT_VER} | sed '1d'`
UP_DB=`echo "UPDATE client SET current_db_vers='${UP_VER}' WHERE client_name='${CLIENT}'" | ${MYSQL_ID}`
while read -r line
 do
  ${UP_DB}
  if [[ "${OUT}" -eq "0" ]]; then
    echo "Database upgraded.."
  else
    echo "Failed to upgrade.."
    exit 1
  fi
done < "${UP_VER}"

由于

希望解决了......我的$ UP_VER连续而不是一列。

2 个答案:

答案 0 :(得分:1)

你误解了几个shell结构的作用:

var=`command`  # This executes the command immediately, and stores
               # its result (NOT the command itself) in the variable

... < "${UP_VER}"  # Treats the contents of $UP_VER as a filename, and tries
                   # to use that file as input

if [[ "${OUT}" -eq "0" ]]; then  # $OUT is not defined anywhere

... current_db_vers='${UP_VER}' ...  # this sets current_db_vers to the entire
                                     # list of versions at once

此外,在shell中,最好使用小写(或混合大小写)变量名称,以避免与具有特殊含义的变量(全部为大写)发生冲突。

要解决第一个问题,我建议不要尝试在变量中存储shell命令,它不能正常工作。 (参见BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!。)要么使用函数,要么直接在命令执行的位置写入命令。在这种情况下,我会投票直接将它直接放在它将要执行的地方。顺便说一句,你在${MYSQL_ID}犯了同样的错误,所以我也建议你修复它。

对于第二个问题,您可以使用<<< "${UP_VER}"将变量的内容作为输入提供(虽然这是一种基础,但在通用posix shell中不可用)。但在这种情况下,我只使用for循环:

for ((ver=db_ver+1; ver<=lt_ver; ver++)); do

对于第三个问题,测试命令成功的最简单方法是将其直接放在if

if somecommand; then
     echo "Database upgraded.."
else # ... etc

所以,这是重写的重点:

mysql_id() {
    # appropriate function definition goes here...
}

for ((ver=db_ver+1; ver<=lt_ver; ver++)); do
  if echo "UPDATE client SET current_db_vers='${ver}' WHERE client_name='${client}'" | mysql_id; then
    echo "Database upgraded.."
  else
    echo "Failed to upgrade.."
    exit 1
  fi
done

...但我不确定我明白应该做什么。它似乎一次更新current_db_vers一个数字,直到达到$ver_lt ...但为什么不在一个UPDATE中直接将其设置为$ver_lt

答案 1 :(得分:0)

尝试类似:

 done <<< "${UP_VER}"
相关问题