bash script use cut command at variable and store result at another variable
Solution 1
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
Solution 2
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
Related videos on Youtube
CodingYourLife
I'm a passionate software developer. Very diversified like Blockchain, Web, Cloud/Backend, Automatic Testing, Machine Learning. Founder and CEO of CodingYourLife e.U.
Updated on July 09, 2022Comments
-
CodingYourLife almost 2 years
I have a config.txt file with IP addresses as content like this
10.10.10.1:80 10.10.10.13:8080 10.10.10.11:443 10.10.10.12:80
I want to ping every ip address in that file
#!/bin/bash file=config.txt for line in `cat $file` do ##this line is not correct, should strip :port and store to ip var ip=$line|cut -d\: -f1 ping $ip done
I'm a beginner, sorry for such a question but I couldn't find it out myself.
-
FatalError about 12 years
for line in cat file
will run twice... once withline=cat
and once withline=file
. I don't think that's what you wanted.
-
-
glenn jackman about 12 years+1 not more efficient, but safer:
for line in $(< file)
will iterate over each word in the file, not each line. -
glenn jackman about 12 years@yourmother, note the use of quotes around the variables here: vital to protect whitespace in the values.
-
glenn jackman about 12 yearsNote the ip can be extracted with
ip=${line%%:*}
without having to call echo|cut. -
jordanm about 12 years@glennjackman
while IFS=: read -r ip _; do
can also be used. -
CodingYourLife about 12 yearsThat's what I was looking for. Thanks! Sorry my answer took so long but I was messing around with how to make a good USB Linux version. With Universal-USB-Installer btw ^^