-2

$VAR2 works fine but $VAR1 returns

shuf: invalid option -- 'c' Try 'shuf --help' for more information.

#!/bin/bash
VAR1="shuf -n 1 file | head -c 5"
VAR2="shuf -n 1 file"
FILE="data"

while IFS="  " read -r COL1 COL2; do
    echo "$($VAR1) $($VAR2) $COL1 $COL2"
done < "$FILE"
1
  • 3
    Please let us know what you want to achieve with this. Do you want to get the first five characters from a random line in a file? If so, why the loop? In general, it's usually a really bad idea to store commands in variables.
    – Kusalananda
    Mar 10, 2018 at 7:04

1 Answer 1

1

The correct way to store command output in a variable is:

VARIABLE="$(command)"

Alternatively, the "old way" (note the backticks):

VARIABLE=`command`

Your code probably will work in this form (haven't tested it myself):

#!/bin/bash
VAR1="$(shuf -n 1 file | head -c 5)"
VAR2="$(shuf -n 1 file)"
FILE="data"

while IFS=" " read -r COL1 COL2; do
    echo "$VAR1 $VAR2 $COL1 $COL2"
done < "$FILE"
3
  • 1
    That looks reasonable. The only thing is the double space in $IFS (the IFS variable holds a collection of characters, not really a string or expression).
    – Kusalananda
    Mar 10, 2018 at 8:51
  • @Kusalananda You're right, corrected. I hadn't had a need to use IFS myself yet. Am i correct to think, that if OP's data file contains only 2 strings per line, divided by whitespace, IFS is unnecessary? I imagine something like: my\first\col my\2nd\col (hence read -r).
    – yahol
    Mar 10, 2018 at 9:22
  • Yes. $IFS does by default contain space, tab and newline. If there are more than two columns, $COL1 will be the first column and $COL2 will contain all the rest. One may want to set IFS to a space if a column contains tabs.
    – Kusalananda
    Mar 10, 2018 at 9:25

Not the answer you're looking for? Browse other questions tagged .