Home > Software design >  echo printing working directory files names for no reason
echo printing working directory files names for no reason

Time:06-24

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:" in the shell gives * index: 1 index: 2 index: 3

CodePudding user response:

pacmd returns * pattern.

In for ... in ...; do ... done loop, the list pattern contains * without any protection.

So, bash replace * by all files found in current directory.

It's the glob functionality.

You could temporary deactivate glob with GLOBIGNORE variable (see 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:

  • The protection with "..." stop glob for bash echo command but do not stop ${...} interpretation.
  • Related