I'm searching for port numbers with grep (in a bash script)
portstr=$(lsof -i -P -n | grep LISTEN | grep sshd)
portstr now looks something like this
sshd 673 root 3u IPv4 14229 0t0 TCP *:22 (LISTEN)
sshd 673 root 4u IPv6 14231 0t0 TCP *:22 (LISTEN)
now I want to extract the numbers between the colon (:) and the following blank space, to get something like this
portarray[0]=>22
portarray[1]=>22
thank you
I tried this
var="[a1] [b1] [123] [Text text] [0x0]"
regex='\[([^]]*)\](.*)'
while [[ $var =~ $regex ]]; do
arr+=("${BASH_REMATCH[1]}")
var=${BASH_REMATCH[2]}
done
from here. But nothing really worked out.
You might use awk by setting the field separator to either 1 or more spaces or a colon using [[:space:]]+|
Check if the first field is sshd, the last field is (LISTEN) and then print the second last field:
portstr=$(lsof -i -P -n | awk -F"[[:space:]]+|:" '$1=="sshd" && $NF == "(LISTEN)" {print $(NF-1)}')
echo "$portstr"
For the output of lsof -i -P -n being:
sshd 673 root 3u IPv4 14229 0t0 TCP *:22 (LISTEN)
sshd 673 root 4u IPv6 14231 0t0 TCP *:22 (LISTEN)
The output of the command:
22
22
Reading this page you can put the output of the command into an array:
portarray=( $(lsof -i -P -n | awk -F"[[:space:]]+|:" '$1=="sshd" && $NF == "(LISTEN)" {print $(NF-1)}') )
for port in "${portarray[#]}"
do
echo "$port"
done
Related
When I want to copy my phone data to my PC using these commands:
Terminal 1
$BUSYBOX nc -l -p 5555 -e $BUSYBOX dd if=/dev/block/mmcblk0
Terminal 2
nc 127.0.0.1 5555 | pv -i 0.5 > $HOME/mmcblk0.raw
I get info that:
1|ASUS_I001_1:/ # /system/xbin/busybox nc -l -p 5555 -e /system/xbin/busybox d>
dd: can't open '/dev/block/mmcblk0': **No such file or directory**
Why?
I have below shell script in which I have two arrays number1 and number2. I have a variable range which has list of numbers.
Now I need to figure out what are all numbers which are in number1 array are also present in range variable. Similarly for number2 array as well. Below is my shell script and it is working fine.
number1=(1220 1374 415 1097 1219 557 401 1230 1363 1116 1109 1244 571 1347 1404)
number2=(411 1101 273 1217 547 1370 286 1224 1362 1091 567 561 1348 1247 1106 304 435 317)
range=90,197,521,540,552,554,562,569:570,573,576,579,583,594,597,601,608:609,611,628,637:638,640:641,644:648
range_f=" "$(eval echo $(echo $range | perl -pe 's/(\d+):(\d+)/{$1..$2}/g;s/,/ /g;'))" "
echo "$range_f"
for item in "${number1[#]}"; do
if [[ $range_f =~ " $item " ]] ; then
new_number1+=($item)
fi
done
echo "new list: ${new_number1[#]}"
for item in "${number2[#]}"; do
if [[ $range_f =~ " $item " ]] ; then
new_number2+=($item)
fi
done
echo "new list: ${new_number2[#]}"
Is there any better way to write above stuff? As of now I have two for loops iterating and then figuring out new_number1 and new_number2 arrays.
Note:
Numbers like 644:648 means, it starts with 644 and ends with 648. It is just short form.
You can use comm with process substitution instead of looping:
mapfile -t new_number1 < <(comm -12 <(printf '%s\n' "${number1[#]}" | sort) <(printf '%s\n' $range_f | sort))
mapfile -t new_number2 < <(comm -12 <(printf '%s\n' "${number2[#]}" | sort) <(printf '%s\n' $range_f | sort))
mapfile -t name reads from the nested process substitution into the named array
printf ... | sort pair provides the sorted input streams for comm
comm -12 emits the items common to the two streams
Aside from codeforester's answer, I can think of two other ways of doing this:
Load the values of $range as keys of an associative array. The
values will be 1. Loop through each member of ${number1[#]} and
${number2[#]}, testing them against the values in the associative
array.
Use codeforester's printf ... | sort trick, but pipe both the list
and the range through sort | uniq -c, then grep for the
duplicates.
I'm not sure if either one of these is an actual improvement on your code. ... I would create a 'find duplicates' shell function, but otherwise your code looks solid.
I've written a shell script to get the PIDs of specific process names (e.g. pgrep python, pgrep java) and then use top to get the current CPU and Memory usage of those PIDs.
I am using top with the '-p' option to give it a list of comma-separated PID values. When using it in this mode, you can only query 20 PIDs at once, so I've had to come up with a way of handling scenarios where I have more than 20 PIDs to query. I'm splitting up the list of PIDs passed to the function below and "despatching" multiple top commands to query the resources:
# $1 = List of PIDs to query
jobID=0
for pid in $1; do
if [ -z $pidsToQuery ]; then
pidsToQuery="$pid"
else
pidsToQuery="$pidsToQuery,$pid"
fi
pidsProcessed=$(($pidsProcessed+1))
if [ $(($pidsProcessed%20)) -eq 0 ]; then
debugLog "DESPATCHED QUERY ($jobID): top -bn 1 -p $pidsToQuery | grep \"^ \" | awk '{print \$9,\$10}' | grep -o '.*[0-9].*' | sed ':a;N;\$!ba;s/\n/ /g'"
resourceUsage[$jobID]=`top -bn 1 -p "$pidsToQuery" | grep "^ " | awk '{print $9,$10}' | grep -o '.*[0-9].*' | sed ':a;N;$!ba;s/\n/ /g'`
jobID=$(($jobID+1))
pidsToQuery=""
fi
done
resourceUsage[$jobID]=`top -bn 1 -p "$pidsToQuery" | grep "^ " | awk '{print $9,$10}' | grep -o '.*[0-9].*' | sed ':a;N;$!ba;s/\n/ /g'`
The top command will return the CPU and Memory usage for each PID in the format (CPU, MEM, CPU, MEM etc)...:
13 31.5 23 22.4 55 10.1
The problem is with the resourceUsage array. Say, I have 25 PIDs I want to process, the code above will place the results of the first 20 PIDs in to $resourceUsage[0] and the last 5 in to $resourceUsage[1]. I have tested this out and I can see that each array element has the list of values returned from top.
The next bit is where I'm having difficulty. Any time I've ever wanted to print out or use an entire array's set of values, I use ${resourceUsage[#]}. Whenever I use that command in the context of this script, I only get element 0's data. I've separated out this functionality in to a script below, to try and debug. I'm seeing the same issue here too (data output to debug.log in same dir as script):
#!/bin/bash
pidList="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25"
function quickTest() {
for ((i=0; i<=1; i++)); do
resourceUsage[$i]=`echo "$i"`
done
echo "${resourceUsage[0]}"
echo "${resourceUsage[1]}"
echo "${resourceUsage[#]}"
}
function debugLog() {
debugLogging=1
if [ $debugLogging -eq 1 ]; then
currentTime=$(getCurrentTime 1)
echo "$currentTime - $1" >> debug.log
fi
}
function getCurrentTime() {
if [ $1 -eq 0 ]; then
echo `date +%s`
elif [ $1 -eq 1 ]; then
echo `date`
fi
}
jobID=0
for pid in $pidList; do
if [ -z $pidsToQuery ]; then
pidsToQuery="$pid"
else
pidsToQuery="$pidsToQuery,$pid"
fi
pidsProcessed=$(($pidsProcessed+1))
if [ $(($pidsProcessed%20)) -eq 0 ]; then
debugLog "DESPATCHED QUERY ($jobID): top -bn 1 -p $pidsToQuery | grep \"^ \" | awk '{print \$9,\$10}' | grep -o '.*[0-9].*' | sed ':a;N;\$!ba;s/\n/ /g'"
resourceUsage[$jobID]=`echo "10 10.5 11 11.5 12 12.5 13 13.5"`
debugLog "Resource Usage [$jobID]: ${resourceUsage[$jobID]}"
jobID=$(($jobID+1))
pidsToQuery=""
fi
done
#echo "Dispatched job: $pidsToQuery"
debugLog "DESPATCHED QUERY ($jobID): top -bn 1 -p $pidsToQuery | grep \"^ \" | awk '{print \$9,\$10}' | grep -o '.*[0-9].*' | sed ':a;N;\$!ba;s/\n/ /g'"
resourceUsage[$jobID]=`echo "14 14.5 15 15.5"`
debugLog "Resource Usage [$jobID]: ${resourceUsage[$jobID]}"
memUsageInt=0
memUsageDec=0
cpuUsage=0
i=1
debugLog "Row 0: ${resourceUsage[0]}"
debugLog "Row 1: ${resourceUsage[1]}"
debugLog "All resource usage results: ${resourceUsage[#]}"
for val in ${resourceUsage[#]}; do
resourceType=$(($i%2))
if [ $resourceType -eq 0 ]; then
debugLog "MEM RAW: $val"
memUsageInt=$(($memUsageInt+$(echo $val | cut -d '.' -f 1)))
memUsageDec=$(($memUsageDec+$(echo $val | cut -d '.' -f 2)))
debugLog " MEM INT: $memUsageInt"
debugLog " MEM DEC: $memUsageDec"
elif [ $resourceType -ne 0 ]; then
debugLog "CPU RAW: $val"
cpuUsage=$(($cpuUsage+$val))
debugLog "CPU TOT: $cpuUsage"
fi
i=$(($i+1))
done
debugLog "$MEM DEC FINAL: $memUsageDec (pre)"
memUsageDec=$(($memUsageDec/10))
debugLog "$MEM DEC FINAL: $memUsageDec (post)"
memUsage=$(($memUsageDec+$memUsageInt))
debugLog "MEM USAGE: $memUsage"
debugLog "CPU USAGE: $cpuUsage"
debugLog "MEM USAGE: $memUsage"
debugLog "PROCESSED VALS: $cpuUsage,$memUsage"
echo "$cpuUsage,$memUsage"
I'm really stuck here as I've printed out entire arrays before in Bash Shell with no problem. I've even repeated this in the shell console with a few lines and it works fine there:
listOfValues[0]="1 2 3 4"
listOfValues[1]="5 6 7 8"
echo "${listOfValues[#]}"
Am I missing something totally obvious? Any help would be greatly appreciated!
Thanks in advance! :)
Welcome to StackOverflow, and thanks for providing a test case! The bash tag wiki has additional suggestions for creating small, simplified test cases. Here's a minimal version that shows your problem:
log() {
echo "$1"
}
array=(foo bar)
log "Values: ${array[#]}"
Expected: Values: foo bar. Actual: Values: foo.
This happens because ${array[#]} is magic in quotes, and turns into multiple arguments. The same is true for $#, and for brevity, let's consider that:
Let's say $1 is foo and $2 is bar.
The single parameter "$#" (in quotes) is equivalent to the two arguments "foo" "bar".
"Values: $#" is equivalent to the two parameters "Values: foo" "bar"
Since your log statement ignores all arguments after the first one, none of them show up. echo does not ignore them, and instead prints all arguments space separated, which is why it appeared to work interactively.
This is as opposed to ${array[*]} and $*, which are exactly like $# except not magic in quotes, and does not turn into multiple arguments.
"$*" is equivalent to "foo bar"
"Values: $*" is equivalent to "Values: foo bar"
In other words: If you want to join the elements in an array into a single string, Use *. If you want to add all the elements in an array as separate strings, use #.
Here is a fixed version of the test case:
log() {
echo "$1"
}
array=(foo bar)
log "Values: ${array[*]}"
Which outputs Values: foo bar
I would use ps, not top, to get the desired information. Regardless, you probably want to put the data for each process in a separate element of the array, not one batch of 20 per element. You can do this using a while loop and a process substitution. I use a few array techniques to simplify the process ID handling.
pid_array=(1 2 3 4 5 6 7 8 9 ... )
while (( ${#pid_array[#]} > 0 )); do
printf -v pidsToQuery "%s," "${pid_array[#]:0:20}"
pid_array=( "${pid_array[#]:20}" )
while read cpu mem; do
resourceUsage+=( "$cpu $mem" )
done < <( top -bn -1 -p "${pidsToQuery%,}" ... )
done
I'm trying to delete specific lines based on the argument passed in.
My data.txt file contains
Cpu 500 64 6
Monitor 22 42 50
Game 32 64 128
My del.sh contains
myvar=$1
sed'/$myvar/d' data.txt > temp.txt
mv temp.txt > data.txt
but it just prints every line in temp.txt to data.txt....however
sed '/64/d' data.txt > temp.txt
will do the correct data transfer (but I don't want to hardcode 64), I feel like there's some kind of syntax error with the argument. Any input please
It's because of the single quotes, change them to double quotes. Variables inside single quotes are not interpolated, so you are sending the literal string $myvar to sed, instead of the value of $myvar.
Change:
sed '/$myvar/d' data.txt
to:
sed "/$myvar/d" data.txt
Note: You will run into issues when $myvar contains regular expression meta characters or forward slashes as pointed out in this response from Ed Morton. If you are not in complete control of your input you will need to find another avenue to accomplish this.
Assuming this is undesirable behavior:
$ cat file
Cpu 500 64 6
Monitor 22 42 50
Game 32 64 128
$ myvar=6
$ sed "/$myvar/d" file
Monitor 22 42 50
$ myvar=/
$ sed "/$myvar/d" file
sed: -e expression #1, char 3: unknown command: `/'
$ myvar=.
$ sed "/$myvar/d" file
$
Try this instead:
$ myvar=6
$ awk -v myvar="$myvar" '{for (i=1; i<=NF;i++) if ($i == myvar) next }1' file
Monitor 22 42 50
Game 32 64 128
$ myvar=/
$ awk -v myvar="$myvar" '{for (i=1; i<=NF;i++) if ($i == myvar) next }1' file
Cpu 500 64 6
Monitor 22 42 50
Game 32 64 128
$ myvar=.
$ awk -v myvar="$myvar" '{for (i=1; i<=NF;i++) if ($i == myvar) next }1' file
Cpu 500 64 6
Monitor 22 42 50
Game 32 64 128
and if you think you can just escape the /s and use sed, you can't because you might be adding a 2nd backslash to one already present:
$ foo='\/'
$ myvar=${foo//\//\\\/}
$ sed "/$myvar/d" file
sed: -e expression #1, char 5: unknown command: `/'
$ awk -v myvar="$myvar" '{for (i=1; i<=NF;i++) if ($i == myvar) next }1' file
Cpu 500 64 6
Monitor 22 42 50
Game 32 64 128
This is simply NOT a job you can in general do with sed due to it's syntax and it's restriction of only allowing REs in it's search.
You can also use awk to do the same,
awk '!/'$myvar'/' data.txt > temp.txt && mv temp.txt data.txt
Use -i option in addition to what #SeanBright proposed. Then you won't need > temp.txt and mv temp.txt data.txt.
sed -i "/$myvar/d" data.txt
I'm writing a script to collect some various network statistics.
What I'm trying to do is to produce some delta data from the netstat -i command.
I'm collecting the needed data with the following bash code:
declare -a array
n=0
netstat -i | tail -n +3 | while read LINE; do
echo "Setting array[$n] to $LINE"
array[$n]=$LINE
echo "array now have ${#array[#]} entries"
let n=$n+1
done
echo "array now have ${#array[#]} entries"
output from this command is:
Setting array[0] to eth0 1500 0 4946794 0 0 0 2522971 0 0 0 BMRU
array now have 1 entries
Setting array[1] to lo 16436 0 25059 0 0 0 25059 0 0 0 LRU
array now have 2 entries
Setting array[2] to vmnet1 1500 0 6 0 0 0 1126 0 0 0 BMRU
array now have 3 entries
Setting array[3] to vmnet8 1500 0 955 0 0 0 1054 0 0 0 BMRU
array now have 4 entries
Setting array[4] to wlan0 1500 0 613879 0 0 0 351194 0 0 0 BMU
array now have 5 entries
array now have 0 entries
As you can see, the array actually disappear after the while loop, and I do not understand why.
Any time you use a pipe you create an implicit subshell. When that subshell terminates, so do its variables. A quick fix for this is to not pipe stuff to read. You can accomplish the above using process substitution:
while read LINE; do
echo "Setting array[$n] to $LINE"
array[$n]=$LINE
echo "array now have ${#array[#]} entries"
let n=$n+1
done < <(netstat -i | tail -n +3)
A more POSIX compliant approach (read: more portable, less bashist) is to make everything happen in the subshell:
netstat -i | tail -n +3 | {
declare -a array
n=0
while read LINE; do
echo "Setting array[$n] to $LINE"
array[$n]=$LINE
echo "array now have ${#array[#]} entries"
let n=$n+1
done
echo "array now have ${#array[#]} entries"
}
You can read the fine points of this (and more) at Greg Wooledge's wiki.
If your only goal is to put the output of a command into an array (linewise), you'd better use the (sadly not very well-known) mapfile bash builtin, it's by far the most efficient (and the best suited for code golf, count how many character strokes I have compared to the other possibilities):
mapfile -t array < <(netstat -i | tail -n +3)
The other answers explain why your construct didn't work (pipe is in a subshell and all that).
help mapfile for all the details and possibilities of that command.
Ok, are you ready?
There is how to transform netstat -i | tail -n +3 in a bash Associative Array of array:
declare -A AANET
while read -a line ;do
declare -a AI$line
eval "AI$line=(${line[#]})"
AANET[$line]=AI$line
done < <(
netstat -i |
tail -n +3)
Than now:
echo ${!AANET[#]}
venet0 eth1 eth0 lo br0
echo ${AANET[eth0]}
AIeth0
And for sub-associative, we have to use eval:
eval echo \${${AANET[eth0]}[#]}
eth0 1500 0 17647 0 0 0 35426 0 0 0 BMPU
eval echo \${${AANET[eth0]}[1]}
1500
eval echo \${${AANET[eth0]}[3]}
17647
eval echo \${${AANET[eth0]}[7]}
35426
eval echo \${${AANET[eth0]}[#]:3:5}
17647 0 0 0 35426
An for assing a temporary variable:
eval currentBin=\${${AANET[eth0]}[3]} currentBout=\${${AANET[eth0]}[7]}
echo $currentBout
35426
echo $currentBin
17647
or even too:
eval "declare -a currentVals=(\${${AANET[eth0]}[#]:3:8})"
echo ${currentVals[0]}
17647
echo ${currentVals[4]}
35426
echo ${currentVals[#]}
17647 0 0 0 35426 0 0 0
Edit:
Ok, if it is possible without eval!
for aKey in ${!AANET[#]};do
fields=(${AANET[$aKey]}{[1],[3],[7]});
echo $aKey ${!fields} ${!fields[1]} ${!fields[2]}
done |
xargs printf "%-9s %12s %12s %12s\n" IFace MTU RX TX
IFace MTU RX TX
venet0 1500 0 0
eth1 1500 6400292 6942577
eth0 1500 17647 35426
lo 16436 83 83
Don't pipe to a loop, bash substitutes variables first and then starts a subshell without access to your array.
Do it like this. Nice and simple.
array=()
for alias in `netstat -i | tail -n +3`; do
array+=($alias)
done
echo ${array[#]}