简体   繁体   English

无缘无故回显打印工作目录文件名

[英]echo printing working directory files names for no reason

why echo printing the files names ?为什么回显打印文件名?

sinks_index=`pacmd list-sinks | grep "index:"`

for i in $sinks_index
    do  
        echo $i
    done

gives this output给出这个输出

audio_name_switcher.sh
audio.py
audio.sh
switch_audio.sh
index:
1
index:
2
index:
3

but running pacmd list-sinks | grep "index:"但运行pacmd list-sinks | grep "index:" pacmd list-sinks | grep "index:" in the shell gives * index: 1 index: 2 index: 3 pacmd list-sinks | grep "index:"在 shell 中给出* index: 1 index: 2 index: 3

pacmd returns * pattern. pacmd返回*模式。

In for ... in ...; do ... donefor ... in ...; do ... done for ... in ...; do ... done loop, the list pattern contains * without any protection. for ... in ...; do ... done循环,列表模式包含*没有任何保护。

So, bash replace * by all files found in current directory.因此,bash 将*替换为当前目录中找到的所有文件。

It's the glob functionality.这是全局功能。

You could temporary deactivate glob with GLOBIGNORE variable (see man bash ):您可以使用GLOBIGNORE变量临时停用glob (请参阅man bash ):

#! /bin/bash
sinks_index='* index: 1 index: 2 index: 3'

GLOBIGNORE="*"
echo "With GLOBIGNORE"
for i in $sinks_index
    do
        echo "UNSET GLOB: " $i
        unset GLOBIGNORE
        echo "  SET GLOB: " $i
        echo "  SET GLOB: $i"
    done
unset GLOBIGNORE

Reactivate global in and after loop.在循环和循环重新激活全局。

  • In: it may be necessary for other stuff;在:可能需要其他东西;
  • After: if your list is empty, the execution do not enter in the loop.之后:如果您的列表为空,则执行不会进入循环。

Note about $i and "$i" after reactivate glob in the loop:注意在循环中重新激活 glob 后的$i"$i"

  • The protection with "..." stop glob for bash echo command but do not stop ${...} interpretation.使用"..." stop glob 保护 bash echo 命令,但不要停止${...}解释。

You should be using an array for sinks_index , not a scalar:您应该为sinks_index使用数组,而不是标量:

sinks_index=( $(pacmd list-sinks | grep "index:") )

for i in "${sinks_index[@]}"
    do  
        echo "$i"
    done

The above will solve the problem you asked about but is making several assumptions about the output of pacmd list-sinks so consider that a starting point but you may need a more robust or slightly different solution depending on that output and what you actually want to do with it.以上将解决您询问的问题,但是对pacmd list-sinks的输出做出了几个假设,因此请考虑这是一个起点,但您可能需要一个更强大或略有不同的解决方案,具体取决于该输出以及您实际想要做的事情用它。

Copy/paste your shell scripts into http://shellcheck.net til you get familiar with shell.将您的 shell 脚本复制/粘贴到http://shellcheck.net直到您熟悉 shell。

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

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