r/bash•
teldon369

Any way to improve code?

help

I'm new to bash and coding in general and created this script to remap a couple of keys that I can't rebind to in-game. Was just wondering if there was any way to improve the code, or if there is really a need to in the first place. Other then that was curious as to why argument in the if statement is set to check if not equal to 1?

#!/bin/bash

# Starting delay
sleep 1 

# Remaps 8,4,5,and 6 to i,j,k, and l respectively using xmodmap and launches Disgaea 2 using its steam URI
xmodmap -e "keycode 80 = i i i i" && xmodmap -e "keycode 83 = j j j j" && xmodmap -e "keycode 84 = k k k k"  && xmodmap -e "keycode 85 = l l l l" && steam steam://run/495280

# Waits 5 seconds to make sure the game is running before starting while loop
sleep 5
while :
do
	# Checks to see if Disgaea 2 is running. How this is done I'm not sure
	# as if statement argument was copied from StackOverflow answer.
	if [[ $(ps -ef | grep -c Disgaea2SteamOS)  -ne 1 ]]
		then
		# If the if statement is true while loop loops.
			sleep 1
		else
		# Otherwise uses set to default US keymap using setxkbmap
		# and leaves while loop.
			setxkbmap
			break
	fi
done 

Posted May 30, 2017, 8:39 PM UTC

43
ropid•

About what's up with that [[ ... -ne 1 ]]:

That grep -c produces a number for how many matches it finds. It will always find at least one match because it will find its own command line in the listing of ps -ef. That's where it will see the text "Disgae2SteamOS" once. When the real Disgaea runs as well, it will then print a two (or more if Disgaea starts several processes with that name).

Another way to do this is with a different tool named pgrep. Your distro probably has it installed by default. Using that one to do the same matching would look like this:

if pgrep -f Disgaea2SteamOS > /dev/null; then
    ...
fi

This uses the exit status of the tool. This works without looking at the tool's output so does not need something like [[ -n $(pgrep ...) ]].

2
teldon369OP•

That makes sense now. And yes I'm on Ubuntu 17.04. I had thought about using pgrep originally when I thought I needed two while loops to do what I wanted. I tried it in the end and it works just the same.

1
hung_kwan•

Rather than messing about grepping ps you can streamline that part of script, forgoing the while loop like so:

until ! ps -C Disgaea2SteamOS >/dev/null 2>&1
do
    sleep 1
done
setxkbmap
1