gpt4 book ai didi

linux - Bash 将值与零进行比较

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:30 25 4
gpt4 key购买 nike

这段bash脚本有什么问题:

OIFS=$IFS;
IFS=$IFS;
IFS=",";
tables=($1);

len="${#tables[@]}";

if [ $len -eq 0 ]; then
tables=("a,b,c");
fi;

IFS=$OIFS

for ((i=0; i < $len; ++i));
do
echo "table ${tables[$i]}";
done

为什么 if [ $len -eq 0 ]; 计算失败?这个想法是如果缺少脚本的参数,则设置默认的表列表。请多多指教!

期望的输出a) 带参数:

./test.sh "x,y,z"
table x
table y
table z

b) 没有参数:

 ./test.sh 
table a
table b
table c

如果这个脚本冒犯了某人,我真的很抱歉,我真的是来这里寻求帮助的,我是 bash 脚本的新手。当有人寻求帮助时,用力逼他真的很让人泄气。我会三思而后行向“bash”社区发布问题。是的,我总是错的,因为我是在寻求帮助,并且是出于善意

干杯

根据您的建议编辑整个工作脚本

#!/bin/bash
#author: sakhunzai
#usages: usage: ./change_db_engine.sh -h [Show help and exit] -u [dbuser] -p[dbpwd] -d[dbname] -e [engine] [csv tables]

NL=$'\n'

function usage() {

echo "$NL $1 $NL
usage: $0 -h [Show help and exit] -u [dbuser] -p[dbpwd] -d[dbname] -e [engine] [csv tables]
Author:sakhunzai$NL";
exit;
}

while getopts ":hu:p:d:e:" opt; do
case $opt in
'h') usage " *** Usage Help **** ";;
'u') usr=$OPTARG;;
'p') pwd=$OPTARG;;
'd') db=$OPTARG;;
'e') engine=$OPTARG;;
\?)
usage "Invalid arguments '-$OPTARG'" ;;
esac
done

if [ -z $usr ] ; then
usage "-u [dbuser] missing";
fi;

if [ -z $pwd ] ; then
usage "-p [dbpwd] missing";
fi;

if [ -z $db ] ; then
usage "-d [dbname] missing";
fi;

if [ -z $engine ] ; then
usage "-e [engine] missing";
fi;


shift $((OPTIND - 1));
# list of tables to be changes separated by comma
IFS=, read -a tables <<< "$1"

if [ "${#tables[@]}" -eq 0 ]; then
tables=($(mysql -u$usr -p$pwd $db -e"show tables" | tr '\n', ' '));
unset tables[0]
tables=( "${tables[@]}" )
fi;

for ((i=0; i < "${#tables[@]}"; ++i));
do
echo "ALTER TABLE ${tables[$i]} ENGINE = InnoDB; ";
done

肯定会有一些丑陋的代码。

最佳答案

tables=("a,b,c") 创建一个包含单个元素 a,b,c 的数组,不是 a列出三个表名。你想要的是 tables=("a""b""c")

整个脚本可以简化为:

if [ $# -eq 0 ]
then
set -- "a" "b" "c"
fi

for table
do
echo "table $table"
done

当然,使用它你必须使用 script.sh foo bar baz 而不是 script.sh foo,bar,baz

关于linux - Bash 将值与零进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22382291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com