Tuesday, February 10, 2015

Rotating display in Ubuntu and Linux Mint - II


In previous post we learnt how we can rotate display in Linux. In this post we'll create a simple function to make it more convenient. We'll split our function in two parts.

Find Screen label

First thing we need to do is to ask user to input the desired screen label that user wants to rotate. From our previous post we know that xrandr -q is the command that can provide us the information regarding each display with its label. We need to identify connected displays only. We'll store this information into an array using mapfile command.
mapfile -t SCREENS < <(xrandr -q | grep ' connected')
Now the "SCREENS" array holds the values for all connected screens. Now we'll present user a choice to select the desired screen.
local PS3="Select Display Screen: "

select SCREEN in "${SCREENS[@]}"
do
  case $SCREEN in
 *)
 break ;;
  esac
done
  
If user has made a valid choice then the "SCREEN" variable holds a string with information regarding the selected screen. We need only the label from that string. We can cut the string using blank space delimiter.
SCREEN=$(echo $SCREEN | cut -d ' ' -f1)

Find Rotation

In Linux you can rotate your monitor in four different positions:
  • normal
  • inverted
  • left
  • right
We'll present a choice to the user to select one of the rotations.
local ROTATIONS=("normal" "inverted" "left" "right")

local PS3="Select Rotation: "

select ROTATION in "${ROTATIONS[@]}"
do
 case $ROTATION in
  "normal") ;;
  "inverted") ;;
  "left") ;;
  "right") ;;
  *) return 0
 esac
done
  
If user has made a valid choice then we can rotate the screen.
xrandr --output "$SCREEN" --rotate "$ROTATION"
Putting it all together:
rotate(){
 local ROTATIONS=("normal" "inverted" "left" "right")
 mapfile -t SCREENS < <(xrandr -q | grep ' connected')
 
 local PS3="Select Display Screen: "

 select SCREEN in "${SCREENS[@]}"
 do
  case $SCREEN in
   *) 
   break ;;
  esac
 done
 SCREEN=$(echo $SCREEN | cut -d ' ' -f1)
 
 if [[ ! $SCREEN ]]
 then
  echo "Sorry, invalid selection!"
 else
 
  local PS3="Select Rotation: "
  
  select ROTATION in "${ROTATIONS[@]}"
  do
   case $ROTATION in
    "normal") ;;
    "inverted") ;;
    "left") ;;
    "right") ;;
    *) echo "Sorry, invalid selection!"
    return 0
   esac
   #putting this line here will make loop keep running until user enters an invalid input.
   xrandr --output "$SCREEN" --rotate "$ROTATION"
  done
 fi
}
  
Now you can add this function to your ~/.bashrc file and can access it from terminal by just typing rotate.