[英]bash script to enter array quantity and fill array data
Today I thought I would write a small bash script to create DB tables on a SQL database.今天我想我会写一个小的 bash 脚本来在 SQL 数据库上创建数据库表。 What I thought would be quick turned out differently.我以为很快就会变成不同的。 Anyway I'm at a mental block and need advice.无论如何,我处于精神障碍,需要建议。 What I was want to do in the end is have the user enter the amount of columns in the table, then specify the column label and data type for the amount they entered to begin with.我最终想要做的是让用户输入表中的列数,然后为他们开始输入的数量指定列标签和数据类型。 Then I'll take the array elements to assemble my SQL server command.然后我将使用数组元素来组装我的 SQL 服务器命令。 It seemed rather obvious to me at first but not so much anymore.起初对我来说似乎很明显,但不再那么明显了。 Any help is appreciated!任何帮助表示赞赏!
I was going to do something like...我要做类似...
#!/bin/bash
echo "Enter database name: "
read dbname
echo "Enter table name: "
read tablename
echo "Enter column count: "
read columns
echo "Enter database username: "
read dbuser
echo "Enter database user password: "
read dbpw
for i in ${columns[@]} do
echo "Column "$i" Name: "
read array_cname[$i]
echo "Column "$i" Data Type: "
read array_ctype[$i]
done
table="USE $dbname CREATE TABLE $tablename(array_cname[] array_ctype[] etc etc etc)"
mysql -u$dbuser -p$dbpw -e "$table"
The above is obviously a broken script, I just whipped it up after having cannibalized what I originally had going.上面显然是一个损坏的脚本,我只是在蚕食了我最初要做的事情后才把它搅起来。
I'm just going to look at the part that you're struggling with - looping over the columns - and you should be able to take these lessons back to your script.我将只查看您正在努力解决的部分 - 遍历列 - 您应该能够将这些课程带回到您的脚本中。
This is what I wrote, omitting the easy bits you've done, and setting columns
to 2, to save typing whilst I tested.这就是我写的,省略了你所做的简单部分,并将columns
设置为 2,以在我测试时节省输入。
#!/bin/bash
columns=2
declare -a cols
for ((i=1; i<=$columns; i++))
do
read -p "Column $i Name: " n
read -p "Column $i Data Type: " t
cols[$i]="$n $t"
done
echo "CREATE TABLE t (${cols[*]} etc etc etc)"
declare
to ensure that our array variable is of the correct type.我使用declare
来确保我们的数组变量是正确的类型。 Bash will infer it's an array when we first assign to an element, but I like to be clear.当我们第一次分配给一个元素时,Bash 会推断它是一个数组,但我想说清楚。1
to $columns
, I use a Bash for
loop.为了枚举从1
到$columns
的整数,我使用了 Bash for
循环。for
and do
.您缺少for
和do
之间的分号或换行符。n
for name and t
for type.我没有尝试直接读入数组元素,而是读入了两个临时变量: n
表示名称, t
表示类型。 I also use -p
to make read
emit the prompt for us.我还使用-p
使read
为我们发出提示。cols+=("$n" "$t")
.如果需要,我可以将它们放入单独的元素中,使用cols+=("$n" "$t")
。${cols[*]}
.为了在替换中扩展数组的所有元素,我使用${cols[*]}
。$ ./36337995.sh
Column 1 Name: a
Column 1 Data Type: int
Column 2 Name: b
Column 2 Data Type: int
CREATE TABLE t (a int b int etc etc etc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.