shell 脚本中的循环 "execute" 命令
For loop "execute" commands in shell script
我想用文本文件的行填充一个数组,其中文件的每一行都是数组中的一个位置,由 space 分隔(例如 array[ 0] = "int", 数组[1]="main(){}", 数组[2]="int" ...)。但在这样做时,一些字符被认为是 shell 命令。下面是要阅读的代码和我的脚本:
Shell 脚本:
#!/bin/bash
array=($(cat ))
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 < "" # <--- HERE
for i in "${array[*]}"; do
echo "$i" # ^--- and HERE (i don't know why)
done
现在可以了! :)
bash的mapfile
命令是你应该在这里使用的:
#!/bin/bash
mapfile -t array < ""
printf "%s\n" "${array[@]}"
我想用文本文件的行填充一个数组,其中文件的每一行都是数组中的一个位置,由 space 分隔(例如 array[ 0] = "int", 数组[1]="main(){}", 数组[2]="int" ...)。但在这样做时,一些字符被认为是 shell 命令。下面是要阅读的代码和我的脚本:
Shell 脚本:
#!/bin/bash
array=($(cat ))
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 < "" # <--- HERE
for i in "${array[*]}"; do
echo "$i" # ^--- and HERE (i don't know why)
done
现在可以了! :)
bash的mapfile
命令是你应该在这里使用的:
#!/bin/bash
mapfile -t array < ""
printf "%s\n" "${array[@]}"