Search code examples
bashescapingaliasquoting

How do I create an alias for a command containing single quotes?


To read the header of the fitsfile I use this command in the bash:

hexdump -e '"%_ad\t" 80/1 "%_p" "\n"' astlimits.fits  | less

Here, the fits file can be downloaded from the website:
http://das.sdss.org/contents/fits/astlimits.fits

Now I tried to create an alias in BASH like this:

alias fitsheader='hexdump -e \'"%_ad\t" 80/1 "%_p" "\n"\''

But, it didn't work.
What is the correct syntax for this so that the following command works:

fitsheader astlimits.fits | less

Solution

  • Nesting of single quotes inside a single-quoted string is not supported in Bash (and other POSIX-compatible shells).

    You can, however, use an ANSI C-quoted string ($'...'), in which ' can be quoted (escaped) as \'.

    alias fitsheader=$'hexdump -e \'"%_ad\t" 80/1 "%_p" "\n"\''
    

    Note that the \t and \n will be expanded to a literal tab and newline up front by the $..., which, however, doesn't make a difference here; when in doubt, double all \ instances in the original string.

    Generally, though, consider using a function, as chepner suggests, as it avoids the quoting headaches and is extensible.