简体   繁体   English

将目录中的文件存储到数组中,然后遍历该数组

[英]Store files in directory into array, then loop through that array

I have a folder called 'sql' that contains .sql files. 我有一个名为“ sql”的文件夹,其中包含.sql文件。 I want to write a script that searches for all .sql files, puts the filename into an array, and then kicks off each file. 我想编写一个脚本,搜索所有.sql文件,将文件名放入数组中,然后启动每个文件。

ie: 即:

 #!/bin/bash

 # Options
 DBHOST=MySQL-hostname
 DBNAME=MySQL-database
 DBUSER=MySQL-username
 DBPASS=MySQL-password

 # Find .sql Files
 ???

 # Create MySQL Tables
 for i in "${TBNAME[@]}"; do
   mysql -h "$DBHOST" -u "$DBUSER" -p"$DBPASS" "$DBNAME" < $TBNAME[$i]
 done

How can I search for .sql files within a specified folder? 如何在指定文件夹中搜索.sql文件?

for sqlfile in sql/*.sql ; do
    # do things to $sqlfile
done

For example you can save the full pathnames in a table by using echo "$PWD/$sqlfile" 例如,您可以使用echo "$PWD/$sqlfile"将完整路径名保存在表中

Late aswer (after accepted one) but for the record: 延迟播种(在接受之后),但为了记录:

printf "source %s\n" sql/**/*.sql | mysql --batch

for this you need to have in the ~/.bash_profile line: 为此,您需要在~/.bash_profile行中:

shopt -s globstar #or put this before the above line

How it works: 这个怎么运作:

printf "source %s\n" sql/**/*.sql 

produces lines like 产生像

source sql/some/file.sql
source sql/other/file2.sql
#and such...

recursively for all found *.sql files, and the 递归地查找所有* .sql文件,并且

mysql --batch .... other arguments

will read the "source filename" lines - and executes the sql commands in the files, all in one execution, not need start (run) multiple times the mysql command... 将读取“源文件名”行-并一次执行所有文件中的sql命令,无需多次启动(运行) mysql命令...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历当前目录并将文件存储在数组中? Bash Shell脚本 - How do you loop through your current directory and store files in an array? Bash shell script VBA遍历目录-存储结果并排序-使用数组? - VBA Loop through Directory - Store Results & Sort - Use Array? 我可以遍历目录和子目录并将某些文件存储在数组中吗? - Can I loop through directories and subdirectories and store certain files in an array? 遍历数组并存储为新数组-Ruby - Loop Through Array and Store as New Array - Ruby C:将目录中的文件列表存储到数组中 - C: Store a list of files in a directory into an array 循环遍历 JSON 数据并将其存储在数组中 - Loop through JSON data and store it in array vba 循环遍历数组,将值存储到 arrayi - vba loop through array, store values to arrayi 如何在数组中存储$ _FILES个超全局变量并遍历它们以在PHP中找到匹配项? - How to store $_FILES superglobal variables in an array and loop through them to find a match in PHP? Excel VBA 仅将选定的文件存储在数组中(不是全部在文件夹中),如果至少选择了一个文件,则循环遍历它们 - Excel VBA store only selected Files in Array (not all in folder) and loop through them if at least one file was selected Mysqli准备的语句:将行存储在数组中,然后在此数组中循环 - Mysqli prepared statement: store rows in an array and loop through this array later
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM