0

I have a txt file with blow format:

66.57.21 - john
88.43.23 - albert
10.10.11 - smith

I wanna to execute "connect.py 66.57.21 john" for each line and I wrote this bash script:

#!/bin/bash
while read LINE; do
awk -v number = "$LINE" '$1'
awk -v name = "$LINE" '$3'
  connect.py $name $number
done < "$1"

but the bash script didn't work

What is the problem

3

2 Answers 2

1
#!/usr/bin/env bash
while read -r number _ name; do
  connect.py "$name" "$number"
done < "$1"
Sign up to request clarification or add additional context in comments.

1 Comment

Hey! connect.py "$name" "$number" < /dev/tty might be safer in case connect.py would read from stdin.
0

If you are wanting to use awk, here is one way to do it:

awk -F" " '{system("connect.py " $3 " " $1)}' input.txt

The -F" " splits each line of input on spaces

$1 is the first word in the array (number in the original question)

$3 is he third word in the array (name in the original question)

wrapping "connect.py " $3 " " $1 in system() causes the shell to execute the command after the substitutions have been made

ie: connect.py john 66.57.21

4 Comments

One thing you want to avoid in scripting is spawning subshells within a loop. That makes shell scripts S L O W.... Here you are spawning 9 subshells every iteration. Command substitution spawns a subshell. Each pipe takes a subshell and you have commands on either side of the pipe. Ouch! If you are reading 1000 or so lines, no problem, if it is 1,000,000 - go get lunch and check back much later. Always try and limit or eliminate this type behavior. Here, if you want to use awk, you can do the entire thing in a single call to awk and use system() for the connection. Advice -- no dings.
Also, you are commiting a UUOc (Unnecessary Use of cat, also stated as Useless Use of cat). Whenever you do cat file ... and are not concatenating files, it is a UUOc. Usually seen as cat file | someUtility. See Useless Use of Cat. Instead all utilities will either take the filenames as an argument or take input on stdin. So it is properly someUtility file or someUtility < file. ... :)
You also have unquoted variables, are using read in a way it'll corrupt lines containing escapes, using all upper case variable names inappropriately, etc. Copy/paste your script into shellcheck.net and it'll tell you about some of the issues.
Thank you both. I have updated based on your collective feedback. Let me know what you think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.