双引号在别名中转义

Double quotation mark escaping in alias

我正在尝试在 Debian Stretch 中设置以下别名

alias myalias='watch -d -n 0.1 '\''find /path -type f -printf '%TY-%Tm-%Td\n' | sort | uniq -c'\'''

我试图用'\''转义第一组引号,但它不适用于周围更深的引号

%TY-%Tm-%Td\n

当我 运行 命令时,我得到以下输出。 %TY-%Tm-%Td\n 周围的引号不再存在,输出不解释 \n,结果在一行上。

Every 0.1s: find /root/bolero/bolero/pkl/stocks -type f -printf %TY-%Tm-%Td\n | sort | uniq -c

有什么想法可以让这项工作成功吗?

您正在寻找的输出是这样的:

alias myalias='watch -d -n 0.1 '\''find /path -type f -printf '\''\'\'''\''%TY-%Tm-%Td\n'\''\'\'''\'' | sort | uniq -c'\'''

当然,这非常复杂。

因为没人要数引号,所以我给大家介绍一个Git你可能不知道的特性:git rev-parse --sq-quote。如果您想知道文本 single-quoted 的正确格式,请改为 double-quote 该部分并将其传递给 git rev-parse --sq-quote。所以逐渐地,它看起来像这样:

$ git rev-parse --sq-quote "find /path -type f -printf '%TY-%Tm-%Td\n' | sort | uniq -c"
 'find /path -type f -printf '\''%TY-%Tm-%Td\n'\'' | sort | uniq -c'
$ git rev-parse --sq-quote "watch -d -n 0.1 'find /path -type f -printf '\''%TY-%Tm-%Td\n'\'' | sort | uniq -c'"
 'watch -d -n 0.1 '\''find /path -type f -printf '\''\'\'''\''%TY-%Tm-%Td\n'\''\'\'''\'' | sort | uniq -c'\'''

这就是您获得结果的方式。请注意,Git 将在行中插入前导 space,为了整洁起见,您可能需要将其删除。