我想用文本文件的行填充一个数组,其中文件的每一行都是数组中的一个位置,由空格分隔(例如 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/