script does not write to file

1

I am mounting a bash script as follows:

#!/bin/bash

destfile=/home/user/teste.txt
array=($(ls 20151* |awk '{ print $9 }'))
n=${array[@]}

echo "$n" > "$destfile"

However, when you run the script, the test.txt file is created, but empty. Except that if you execute the commands one by one in the terminal, the file is created with the content exactly the way I need it. What am I doing wrong?

    
asked by anonymous 12.01.2016 / 13:06

2 answers

2

By default, awk parses a string using the whitespace character as a separator.

So if this is done:

echo "20151223152832_alexsandro_felix.txt" | awk '{print $9}'

Nothing will be returned, as there is no blank space in the string, and even if it does, it would take 8 spaces to print something at position 9.

Now try changing the string, including a space:

echo "20151223152832 _alexsandro_felix.txt" | awk '{print $1}'

Will be returned: 20151223152832

echo "20151223152832 _alexsandro_felix.txt" | awk '{print $2}'

Will be returned: _alexsandro_felix.txt

The command ls -lh returns a string in this format:

-rw-rw-r-- 1 cantoni cantoni 0 Jan 12 10:39 20151223152832_alexsandro_felix.txt

So, by making a awk '{print $9}' the file name is printed. The danger of this approach is if the file name contains spaces. If this happens then awk '{print $9}' will not return the whole file name.

Explained, one way to resolve this problem without using awk would be by using the following command:

ls -A 20151*

In the context of the question question would this be:

array=($(ls -A 20151*));

You can change the separator by which awk does split in a string, see example below:

echo "20151223152832:_alexsandro_felix.txt" | awk -F':' '{print $2}'

Will be returned: _alexsandro_felix.txt

In this case, the separator was the character ':'

    
12.01.2016 / 14:10
2

I discovered my error, in fact as I have in my user an alias for ls I ended up getting used to it, so really the error was in the line that @cantoni quoted. To fix it I did this:

#!/bin/bash

destfile=/home/user/file.txt;
array=($(ls -lh 20151* |awk '{ print $9 }'));
n=${#array[@]};

echo "$n" > "$destfile";
    
12.01.2016 / 13:43