0

I want to populate an array with the lines of a text file, where each line of the file is a position in the array, separated by a space (for example array[0] = "int", array[1]="main(){}", array[2]="int"...). But in doing so, some characters are considered as shell commands. Below the code to be read and my script:

Shell Script:

#!/bin/bash

array=($(cat $1))

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

Source code to be read:

int main(){

    int i;

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

    return 0;
}

Output:

 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;
}

Thanks for the help!

-- UPDATE --

I had to make two changes to the script (thanks glenn jackman):

#!/bin/bash

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

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

Now it works! :)

2
  • 2
    Not coincidentally this is BashFAQ/001. Commented Feb 25, 2015 at 21:11
  • Basically the first statement is this haha. Thanks a lot! :D Commented Feb 25, 2015 at 21:18

1 Answer 1

1

bash's mapfile command is what you should use here:

#!/bin/bash
mapfile -t array < "$1"
printf "%s\n" "${array[@]}"
Sign up to request clarification or add additional context in comments.

2 Comments

I've found the problem: my script cannot display the /* sequence. Somewhere in the text file there is a sequence of characters /*, indicating the start of a comment in C-style and I can not escape the asterisk.
That indicates you are not quoting a variable somewhere: bash will perform word splitting and filename generation on unquoted variables -- gnu.org/software/bash/manual/bashref.html#Shell-Expansions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.