Visit Our UNIX and Linux User Community

False positive grep?

Thread Tools Search this Thread
Top Forums Shell Programming and Scripting False positive grep?
# 1  
Old 04-15-2020
False positive grep?


While I was working a bit on pick, my select emulator, I started to get an endless loop...

I could point it down to my 'arrow-keys catch code':
# Check for arrow keys
builtin echo "$NUM" | $GREP -q '^\[\[' && continue

However, while running the code - with regular (expected numeric input)... it becomes this:
++ builtin echo 6
++ grep -q '^\[\['
++ continue

Which definitly is NOT what I had expected as behaviour.
Any ideas why I get this 'false positive'?

Thank you in advance

It is even worse / more weird...
		# Catch invalid inputs
			set -x
			# Keep reading if NUM is empty
			[[ -z "$NUM" ]] && continue
			# Also keep reading if NUM length = 0 ; is this even required?
			[[ ${#NUM} -eq 0 ]] && continue
			# Keep reading if NUM contains letters
			# Using builtin echo for speed and less disk usage
			builtin echo "$NUM" | $GREP -q [a-zA-Z]  && continue	# &2>/dev/zero
			# Check for arrow keys
			builtin echo "$NUM" | $GREP -q '^\[\[' && continue

[[ -z 5 ]]                                                                                              | #
++ [[ 1 -eq 0 ]]

++ builtin echo 5
++ grep -q '[a-zA-Z]'
++ builtin echo 5
++ grep -q '^\[\['
++ continue

Now, I did comment out the the ^[[-code part, just so it fails at the [a-zA-Z] already....
[[ -z 4 ]]                                                                                              | #
++ [[ 1 -eq 0 ]]

++ builtin echo 4
++ grep -q '[a-zA-Z]'
++ continue


Last edited by sea; 04-15-2020 at 01:54 PM..
# 2  
Old 04-15-2020
The grep args should be quoted so the shell does not try a filename generation.
builtin echo "$NUM" | $GREP -q "[a-zA-Z]"  && continue

These 2 Users Gave Thanks to MadeInGermany For This Post:
# 3  
Old 04-15-2020
Thank you, but nope.

Still fails.
It passes [a-zA-Z] (double & single quotes) just to fail at the '^\[\[' line AFTERwards....
But either way, the "++debug output showed single quotes in the first post, despite not having them.

Closed terminal... started a new one and now....

No colors/borders anymore... FFFFFF=white of anger....

Bet the issue was somewhere there (in the env-memory of said now-closed terminal window-tab).....
All my (obviously imagined) fixes.. worthless... once more... again....

I'm back to square one... to fix the display-functions that i THOUGHT were working yesterday evening.. 24 hrs ago... WTF?!?!
No more coding today...
# 4  
Old 04-16-2020
I do remember you being quite concerned with performance in this SWARM stuff and I would have thought the bash =~ operator could be use in place of grep.

$ export NUM='[['
$ time bash -c 'echo "$NUM" | grep -q "^\[\[" && echo yes'

real    0m0.200s
user    0m0.000s
sys     0m0.107s
$ time bash -c '[[ "$NUM" =~ ^\[\[ ]] && echo yes'

real    0m0.099s
user    0m0.015s
sys     0m0.046s

Twice as fast on my system, but your mileage may vary
This User Gave Thanks to Chubler_XL For This Post:
# 5  
Old 04-18-2020
Sorry for that outbreak...

But it's working now, thank you MIG & Rav, though, mostly because I droped 'those' catches alltogether...
Here's the full working pick:
	pick() { # [-1 -2 -a -m] $LIST or ${ARRAYS[@]}
	# Select an item of a LIST or an ARRAY
	# Returns the value
		# Variables
			local counter=0
			local AUTO=false
			local ROWS="3"
			local as_menu=false
		# Catch arguments
			for opt in "${@}"
			do	if [[ "-" == "${opt:0:1}" ]] 
				then	case "${opt/-}" in
					1|2|3)	ROWS="${opt/-}"
					"a")	AUTO=true
					"m")	trap "return 130" INT ABRT KILL
					"-")	wasPipe=true
			# Can not be set earlier because of possible options
			# Which state wether it is 'as menu' or default
			$as_menu && \
				local ARGS=( "${SWARM_MSG_PICK_BACK}" "${@}" ) || \
				local ARGS=("${@}")
		# Pipe handling
		# It's different when working with 'read'
			#[ -z "$1" ] && \
			#	while IFS= read -r ARG
			#	do	set -- "$@" "$ARG" && wasPipe=true
			#	done
		# Handle auto-pick (only 1 option)
			"$AUTO" && \
				[ "$#" -eq 1 ] && \
				$PRINTF '%s\n' "$ARGS" >&1 && \
				return 4
		# Show the items to pick from
			#set +x
			$as_menu && \
				printlist -n -$ROWS -0 ${ARGS[@]} || \
				printlist -n -$ROWS "${ARGS[@]}"
			#set -x
		# Set dynamic values
			# Amount of arguments
			local pick_count=${#ARGS[@]}
			# Character length of the amount
			local pick_len=${#pick_count}
			#Special handling
			local invalid=true
			local NUM=""
			local POS="$(swarm.print.goto $(( $identRight + 2 )))${SWARM_THEME_DATA[read]} "
			$as_menu && \
				local min=0 || \
				local min=1
		# Visuals
		while $invalid
			# Except the best, prepare for the worst
		# Print the input line:
			$PRINTF "$POS      $POS" >&2
		# Read the input 
			builtin read -n $pick_len NUM
		# Catch invalid inputs
			# Keep reading if NUM is empty
			[[ -z "$NUM" ]] && continue
			# Check if NUM is numeric
			if [[ ${#NUM} -ge 0 ]] &2>/dev/zero
				# If it's exactly 0, it's BACK
				[[ ${#NUM} -eq 0 ]] && $ECHO "${ARGS[$NUM]}" && return
				# It's not zero but some other numeric input
				# Keep reading if it is not greater than 'min'-imum
				[[ ${NUM} -ge $min ]] &2>/dev/zero || continue
				# Keep reading if it is greater than pick_count
				[[ $NUM -gt $pick_count ]] && continue
				# Exit the loop
				# It's not a number, catch other cases
			# Actualy, all checks below are (can be) left out....	
				# Keep reading if NUM contains letters
				# Using builtin echo for speed and less disk usage
				builtin echo "$NUM" | $GREP -E -q "[a-zA-Z]"  && continue	# &2>/dev/zero
				# Check for arrow keys
				#builtin echo "$NUM" | $GREP -E -q "^\[\[" && continue
				[[ "$NUM" =~ '^[[' ]] && continue
				# Keep reading if NUM is longer than $pick_len
				# ?? This SHOULD catch arrow-keys in most real usage cases
				[[ ${#NUM} -gt ${pick_len} ]] &2>/dev/zero && continue
		# Make 'nice to have' line break when read automatically stops reading
		if [ "${#NUM}" -eq "${#len}" ] 
		then	# Only print newline character if the entered number as the longest number
			# But not sub zero
			[ "${NUM}" -ne -1 ] && $PRINTF "\n" >&2
		else	# Since arrays are 0 indexed, 10 becomes 9 and need special treatment
			[ "${NUM}" -eq 9 ] && $PRINTF "\n" >&2
		$as_menu || NUM=$(( $NUM - 1))
		# Prepare output
		$ECHO "${ARGS[$NUM]}"
		unset opt

This User Gave Thanks to sea For This Post:
# 6  
Old 04-19-2020
Consequently you should replace the other grep -E -q with a [[ =~ ]].

And &2>/dev/zero looks odd. Perhaps you mean 2>/dev/null but this is not appropriate after a [[ ]] compound.
# 7  
Old 04-19-2020
Good morning MIG Smilie

Yes, I'm always getting confused whether to use /dev/null or /dev/zero, because most of the *nix flavors I use, have both.

if [[ ${#NUM} -ge 0 ]] &2>/dev/null

Yes, this might be unususal, but it helps to avoid parsing errors -> well the visual breakup <- when 'catching' arrow keys (NOT specificly).

Are you refering to the other '^[[' line just above - which is commented out, or to the '[a-zA-Z]' grep to be changed to ~=?
But basicly, neither of those lines are 'now' executed, because it's 'all' left out anyway - to my understanding - the only reason it's still there, is because I just had it rewritten it compared to the initial post (before sleeping).
				# It's not a number, catch other cases
			# Actualy, all checks below are (can be) left out....

Or am I missing a point of yours?
Thank you.

Previous Thread | Next Thread
Test Your Knowledge in Computers #64
Difficulty: Easy
HTTP uses UDP as the core transport protocol on the Internet.
True or False?

8 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

False alerts

Hi I have written a script to send email alerts when load of my linux server reaches max point I keep getting false emails thought the load is normal , looks like same email is generated again and again - called from cron tab checked if the tempfile is present , no it is not , cleaned... (22 Replies)
Discussion started by: anil529
22 Replies

2. UNIX for Dummies Questions & Answers

Tail with positive offset

I have read the below from the book bash cookbook.Tail +1 filenames is similar to cat filename I have tried the same in Ubuntu 11.10 with bash. 4.0 . I have received error for the Same. May I know in which system that will work fine ? Thanks (1 Reply)
Discussion started by: pandeesh
1 Replies

3. AIX

Gid=0 and 7 + admin=FALSE

Checking configuration access files for an AIX server, left me wondering about this :confused:: If a user is added to system group, it gets gid=0 with some security risks because it gets some root kind of file access level. Is this insecure condition kept if the user has admin variable... (0 Replies)
Discussion started by: bkiddo
0 Replies

4. IP Networking

false tcp connection

Why this happens? How to solve this? $netstat -na |grep 9325 tcp 0 0 ESTABLISHED When a client socket repeatedly tries to connect to an inactive(no server socket is listening on this port) local port,connect succeeds. ... (1 Reply)
Discussion started by: johnbach
1 Replies

5. Shell Programming and Scripting

False Condition

Hi All, I am using the below Script to enter a line in the File: #!/bin/ksh # To delete the last line if it contains the pattern Redirect permanent / Virgin Atlantic Airways - Popup echo "Enter the URL that should point to the particular microsite" read url # To delete the last line if it... (0 Replies)
Discussion started by: Shazin
0 Replies

6. Shell Programming and Scripting

Why is it always false?

Hi, I'm new to UNIX and am trying to learn shell scripting in order to work on an interface that I inherited when a co-worker left. I need to be able to check to see whether a file exists to determine whether the FTP has taken place, but in testing, the if statement always evaluates as false,... (3 Replies)
Discussion started by: JeffR
3 Replies

7. Shell Programming and Scripting

false use of sed???

i want to delete every newline and every line which starts with "RECORD......." in a file. FILE: Record 61391 in base BROCKHAUS (Timestamp: 2008-04-09 11:38:38) UNTERTITEL : Gräfin (seit 1707 Reichsgräfin) von, * Schwerin 4. 2. 1686, + Berlin 21. 10. 1744; wurde Record 61392 in base BROCKHAUS... (4 Replies)
Discussion started by: trek
4 Replies

8. Linux


We have requirments to not allow a userid login abilities but allow users to 'su' to it. In solaris I normally set the shell in /etc/passwd to bin/false. THis does not work on Linux, any suggestions would help. (1 Reply)
Discussion started by: bryanthomas
1 Replies

Featured Tech Videos