arrays - For 循环 "execute"shell 脚本中的命令

标签 arrays linux shell loops for-loop

我想用文本文件的行填充一个数组,其中文件的每一行都是数组中的一个位置,由空格分隔(例如 array[0] = "int"array[1]="main(){}"array[2]="int"...)。但是在这样做时,一些字符被认为是 shell 命令。下面是要阅读的代码和我的脚本:

shell 脚本:

#!/bin/bash

array=($(cat $1))

for i in "${array[@]}"; do
  echo "$i"
done

需要阅读的源码:

int main(){

    int i;

    /** /** **/ (this part is treated as a shell command)
    i = 3 + 2;

    return 0;
}

输出:

 p0ng   ~ > ~/Compiladores  sh teste.sh codigoFonte.c 
int
main(){
int
i;
/bin
/boot
/dev
/etc
/home
/lib
/lib64
/lost+found
/mnt
/openwrt
/opt
/proc
/root
/run
/sbin
/srv
/sys
/tmp
/usr
/var
/bin
/boot
/dev
/etc
/home
/lib
/lib64
/lost+found
/mnt
/openwrt
/opt
/proc
/root
/run
/sbin
/srv
/sys
/tmp
/usr
/var
Projeto/
i
=
3
+
2;
return
0;
}

感谢您的帮助!

-- 更新--

我不得不对脚本进行两​​处更改(感谢 glenn jackman):

#!/bin/bash

mapfile -t array < "$1" # <--- HERE

for i in "${array[*]}"; do
  echo "$i"     # ^--- and HERE (i don't know why)
done

现在可以了! :)

最佳答案

bash 的 mapfile命令是你应该在这里使用的:

#!/bin/bash
mapfile -t array < "$1"
printf "%s\n" "${array[@]}"

关于arrays - For 循环 "execute"shell 脚本中的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28729626/

相关文章:

php - 从数据库条目在 PHP 中创建变量

linux - Centos apache Web 服务器抛出 403 错误

bash - grep -vf 大文件太慢

linux - Bash 将信息从脚本传递到脚本

linux - BASH grep 脚本

bash - Basename 无法接收带破折号的文件名

javascript - 在数组数组中搜索数组的最有效方法

java - 如何在java中的通用数组中使用compareTo?

javascript - Angular ng-选项 : iterate over a number array for displaying content of an other array but having index chosen in ng-model

java - 已解决 : JVM hangs forever with no CPU usage or I/O