简体   繁体   English

在命令执行之前阻止 Bash 扩展通配符

[英]Stop Bash from expanding a wildcard before command execution

I have a boot script /init that starts a Linux embedded system.我有一个启动 Linux 嵌入式系统的启动脚本/init In there I have a function that counts partitions from an SD-Card在那里我有一个功能可以计算 SD 卡中的分区

get_number_of_partitions () { ls ${SDCARD_DEV}p* 2> /dev/null | wc -l; }

It works with some busybox versions, but not all versions.它适用于一些 busybox 版本,但不是所有版本。 The expectation is to count partitions, like /dev/mmcblk0p1 /dev/mmcblk0p2 .期望是计算分区,例如/dev/mmcblk0p1 /dev/mmcblk0p2 When I traced down, I find that with non-working cases, the p* is expanded to proc before the ls command.当我追踪时,我发现在非工作情况下, p*ls命令之前扩展为proc Resulting in counting 1 instance of ${SDCARD_DEV} + about 100 items from proc children.导致计算${SDCARD_DEV} 1 个实例 + 来自proc子项的大约 100 个项目。

I also tried: ls ${SDCARD_DEV}"p*" which gave the same result.我也试过: ls ${SDCARD_DEV}"p*"给出了相同的结果。

The only way I can think of that this would happen is if ${SDCARD_DEV} ends with whitespace, eg我能想到的唯一方法是如果${SDCARD_DEV}以空格结尾,例如

SDCARD_DEV="/dev/ "

As a result, the command being executed is结果,正在执行的命令是

ls /dev/ p*

instead of代替

ls /dev/p*

Disabling the wildcard expansion won't solve this problem.禁用通配符扩展不会解决这个问题。 First of all, ls doesn't do wildcard expansion itself, it depends on the shell expanding the wildcard before invoking it.首先, ls本身不进行通配符扩展,它依赖于在调用通配符之前扩展通配符的外壳。 Second, ls would still see these as two separate arguments, it wouldn't interpret p* as being files to match inside /dev .其次, ls仍会将它们视为两个单独的参数,它不会将p*解释为要在/dev匹配的文件。

Ideally you should figure out why the space is being added to the variable in the first place, and fix that.理想情况下,您应该首先弄清楚为什么将空间添加到变量中,然后解决这个问题。 If not, you can remove it before using the variable:如果没有,您可以在使用变量之前将其删除:

SDCARD_DEV="$(sed 's/ *$//' <<< "$SDCARD_DEV")"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM