$VAR2 works fine but $VAR1 returns

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

VAR1="shuf -n 1 file | head -c 5"
VAR2="shuf -n 1 file"

while IFS="  " read -r COL1 COL2; do
    echo "$($VAR1) $($VAR2) $COL1 $COL2"
done < "$FILE"

closed as unclear what you're asking by Rui F Ribeiro, Sparhawk, DarkHeart, Kusalananda, GAD3R Mar 10 '18 at 14:55

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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 '18 at 7:04

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


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


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

VAR1="$(shuf -n 1 file | head -c 5)"
VAR2="$(shuf -n 1 file)"

while IFS=" " read -r COL1 COL2; do
    echo "$VAR1 $VAR2 $COL1 $COL2"
done < "$FILE"
  • 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 '18 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 '18 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 '18 at 9:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.