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.


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

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)

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

$ cat myItems
$ for item in $(cat myItems);do
    USER=$(echo $item | cut -d ":" -f1)
    PASS=$(echo $item | cut -d ":" -f2)
    echo user $USER pass $PASS
user user pass pass
user user2 pass pass2
| improve this answer | |
  • 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 – Anthony Russell Dec 4 '16 at 22:33
  • Indeed, you were cating a variable, rather than echoing. – steve Dec 4 '16 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. – Stéphane Chazelas Dec 5 '16 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 '16 at 16:15

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.

| improve this answer | |
  • 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? – Anthony Russell Dec 5 '16 at 13:50

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.