0

I'm attempting to run a bash command on a forloop object but it's trying to look for a file instead of use the forloop object.

Example:

The input file contains lines in the format of user:password

for item in $(cat myItems);do
        USER = cat $item | cut -d ":" -f1
        PASS = cat $item | cut -d ":" -f2
done

The result of this is that it says File $item isn't found

I also tried

for item in $(cat myItems);do
        USER = $(cat $item | cut -d ":" -f1)
        PASS = $(cat $item | cut -d ":" -f2)
done
0

2 Answers 2

5

If you do indeed need to run some command for every line of the file, you'd write:

while IFS=: read -r user password rest_ignored; do
  something with "$user" and "$password"
done < myItems

cat is the command to concatenate files, the assignment syntax is var=value without spaces around =. $(...) can split the output of a command on newline but only if you set $IFS properly and disable globbing.

1
  • Can you please elaborate on how your example knows that the colon is the deliminator between the username and password in the input file stream? Dec 5, 2016 at 13:50
3

This appears to achieve what you're after, and keeps to the script approach you originally intended.

$ cat myItems
user:pass
user2:pass2
$ for item in $(cat myItems);do
    USER=$(echo $item | cut -d ":" -f1)
    PASS=$(echo $item | cut -d ":" -f2)
    echo user $USER pass $PASS
done
user user pass pass
user user2 pass pass2
$
4
  • Interesting so it's more a problem with the cat command not taking variables instead of me not being able to use bash commands on variables Dec 4, 2016 at 22:33
  • Indeed, you were cating a variable, rather than echoing.
    – steve
    Dec 4, 2016 at 22:41
  • For $(cat myItems) to split on newline characters only, you need IFS=$'\n'. You also need to issue a set -o noglob for the *?[ characters in there not to be taken specially. You can't use echo for arbitrary data, you need to quote variables so they are not split+globed. Dec 5, 2016 at 15:38
  • That said, if you're dealing with simple text like 'user' and 'pass' in the fields, it's perfectly suitable.
    – steve
    Dec 5, 2016 at 16:15

You must log in to answer this question.

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