Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script use cut command at variable and store result at another variable

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.

like image 974
CodingYourLife Avatar asked Mar 15 '12 18:03

CodingYourLife


People also ask

How do you store the output of cut command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you cut a variable command in Unix?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.

What does $@ do in bash script?

Symbol: $# The symbol $# is used to retrieve the length or the number of arguments passed via the command line. When the symbol $@ or simply $1, $2, etc., is used, we ask for command-line input and store their values in a variable.


2 Answers

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.

like image 82
shellter Avatar answered Sep 23 '22 16:09

shellter


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

like image 33
anubhava Avatar answered Sep 26 '22 16:09

anubhava