3

I wanted to make an alias turn caps lock off:

python -c 'from ctypes import *; X11 = cdll.LoadLibrary("libX11.so.6"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)'

I wrote this into my .zshrc:

alias caps='python -c 'from ctypes import *; X11 = cdll.LoadLibrary("libX11.so.6"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)' '

But it seems that the problem is that I have ' in the command (so it make an alias to a part of it).

I tried to use:

alias caps=" python -c 'from ctypes import *; X11 = cdll.LoadLibrary("libX11.so.6"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)' "

to see if something changed and I get python's sintax error.

So how can I make an alias to a one-liner with ' inside?

jinawee
  • 187
  • 6

3 Answers3

2

You need to escape the double quotes in the python script:

alias caps="python -c 'from ctypes import *; X11 = cdll.LoadLibrary(\"libX11.so.6\"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)' "

Of course, you could also save that as a python script, and then

alias caps='path/to/script.py' 
terdon
  • 242,166
1

Generally speaking, the easy way to quote a string (such as a shell command) that can contain arbitrary characters is:

  • Replace all single quotes ' in the string by the 4-character sequence '\''.
  • Put single quotes '…' around the string.

See Wrapping a command that includes single and double quotes for another command for more details.

Thus (with an optimization on the last character which happens to be a single quote):

alias caps='python -c '\''from ctypes import *; X11 = cdll.LoadLibrary("libX11.so.6"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)'\'

However, rather than dwell into such complexities, just make it a function.

caps () {
  python -c 'from ctypes import *; X11 = cdll.LoadLibrary("libX11.so.6"); display = X11.XOpenDisplay(None); X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0)); X11.XCloseDisplay(display)'
}

Or make it a script.

0

Use a function or make a script.

caps() python -c '
from ctypes import *
X11 = cdll.LoadLibrary("libX11.so.6")
display = X11.XOpenDisplay(None)
X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(2), c_uint(0))
X11.XCloseDisplay(display)'