为什么 sh 对这些命令的解释与 zsh 不同? [英] Why does sh interpret these commands differently to zsh?

查看:50
本文介绍了为什么 sh 对这些命令的解释与 zsh 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:我正在尝试获取 Linux 机器上安装的字体名称.名称在两个冒号之间.当我使用 zsh 运行此脚本时,它可以工作.当我切换到 sh 时,它会中断.它可能会删除 \n 个字符,因为输出都是一行.

cmd=$(fc-list)";names=$(echo $cmd | grep -oP "(?<=: ).*?(?=:)")"回声 $names

哪个命令会导致问题?它不符合 POSIX 标准吗?

解决方案

为什么 sh 对这些命令的解释与 zsh 不同?

因为是不同的shell所以规则也不同.

<块引用>

哪个命令会导致问题?

echo $cmd

echo $names

<块引用>

它不符合 POSIX 标准吗?

代码本身就是有效的 POSIX 代码.zsh shell不做分词的行为不符合POSIX.

在 POSIX shell 中,不带引号的扩展会进行分词.因为默认的 IFS 是空格制表符和换行符,所以这些字符在从扩展结果中创建单词时会被删除,并作为单独的单词传递给 echo,后者将它们在一行上输出.要禁用分词(和文件名扩展),您需要引用扩展.也更喜欢 printfecho.

cmd=$(fc-list)";names="$(printf "%s\n" "$cmd" | grep -oP "(?<=: ).*?(?=:)")";printf "%s\n";$names"

Context: I am trying to get the names of fonts installed on my Linux machine. The name is between two colons. When I run this script using zsh, it works. When I switch to sh it breaks. It probably deletes \n characters, because the output is all one line.

cmd="$(fc-list)"
names="$(echo $cmd | grep -oP "(?<=: ).*?(?=:)")"
echo $names

Which command causes the issues? Is it not POSIX compliant?

解决方案

Why does sh interpret these commands differently to zsh?

Because they are different shell the rules are different.

Which command causes the issues?

echo $cmd

and

echo $names

Is it not POSIX compliant?

The code, by itself, is valid POSIX code. The behavior of zsh shell that doesn't do word splitting is not compliant with POSIX.

In POSIX shell unquoted expansions undergo word splitting. Because default IFS is space tab and newline, these characters are erased when creating words from the result of expansion and passed as separate words to echo which outputs them on one line. To disable word splitting (and filename expansion), you need to quote the expansion. Also prefer printf to echo.

cmd="$(fc-list)"
names="$(printf "%s\n" "$cmd" | grep -oP "(?<=: ).*?(?=:)")" 
printf "%s\n" "$names"

这篇关于为什么 sh 对这些命令的解释与 zsh 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆