Search code examples
bashechocut

Cut / echo inside bash


Im confused with how the following cut works in the bash script.

Sample of file.csv:

#10.10.10.10;28;9.10.10.10: up;Something ;More random spaces

My script:

#!/bin/bash

csv_file="file.csv"

locations=( $( cut -d';' -f5 $csv_file ) )

for ((i=0; i < ${#locations[@]}; i++))
do
   echo "${locations[$i]}"
done

The result of the script is:

More
random
spaces

When I just copy and paste the cut in my CLI without any echos or variables the cut works as I´d expect and prints:

More random spaces

I am sure it´s some bracket or quote problem, but I just can't figure it out.


Solution

  • Your command substitution $(...) undergo's word splitting and pathname expansion:

    a="hello world"
    arr=($(echo "$a")); # Bad example, as it could have been: arr=($a)
    
    echo "${arr[0]}" # hello
    echo "${arr[1]}" # world
    

    You can prevent this by wrapping the command substitution in double quotes:

    arr=( "$(...)" )
    echo "${arr[0]}" # hello world
    

    Same applies to parameter expansions, eg:

    a="hello world"
    printf "<%s>" $a   # <hello><world>
    printf "<%s>" "$a" # <hello world>