Search code examples
bashvariable-assignmentcommand-substitution

Bash unable to assign value


Got a bit of a problem. I'm new to bash and I'm trying my hardest, but I can't figure out how to assign the desired output to the variable. Running this command in the prompt

wc -l data.txt | awk '{ print $1 }'

yields the result 12, which is desired. However if I put it in the test.sh file, it won't work. I've tried different quotations, but all I've managed to get is the entire line as a string...

Test.sh

#! /bin/bash

# Count lines for data.txt files
data1=wc -l data.txt | awk '{ print $1 }'

echo "Lines in data.txt: $data1"

exit

Solution

  • I think you want:

    data1="$(wc -l data.txt | awk '{ print $1 }')"
    

    The $() syntax causes bash to execute that expression and replace it with the results.

    Actually, powershell does allow you to do a straight = assignment like you did...