1

hey im new to bash and for some reason I cant store the output into a variable

#!/bin/bash
file="~/cs/cs3776/assignment2/passwd1.txt"
while read p; do

        echo "$p" | cut -d: -f1





done < passwd1.txt

changing the echo to

$a=$(echo "$p" | cut -d: -f1)
echo "$a"

doesnt seem to work

  • Besides changing the echo command as you have shown, what have you done to try to diagnose this? Are you getting any output at all? Are you sure that the passwd1.txt file has text in it? Is it formatted like /etc/passwd? If not, please show us what it looks like — it doesn't have to be your actual data, just something to illustrate the format. P.S. say a=..., not $a=.... – G-Man Feb 28 '17 at 2:05
1

There are two problems here. The one you're seeing is that you're using a dollar sign on the variable you're assigning to -- the dollar sign is used to get the value of a variable, not to set it. Thus, use a=$(echo "$p" | cut -d: -f1) instead of $a=$(echo "$p" | cut -d: -f1).

The second problem is in the assignment file="~/cs/cs3776/assignment2/passwd1.txt" -- the ~ needs to be expanded to the path to your home directory, but that expansion doesn't happen when it's in double-quotes. In this case, there's nothing else there that'd be expanded, so just leaving off the quotes (file=~/cs/cs3776/assignment2/passwd1.txt) would work. If quotes were needed for the rest of the string, it's possible to partially-quote the string (file=~/"cs/cs3776/assignment2/passwd1.txt").

  • What you wrote about the second problem is right in general, it's good you have spotted this. In this particular case it changes nothing because $file is never used. – Kamil Maciorowski Jul 21 '18 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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