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:"
in the shell gives * index: 1 index: 2 index: 3
pacmd
returns *
pattern.
In for ... in ...; do ... done
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.
Note about $i
and "$i"
after reactivate glob in the loop:
"..."
stop glob for bash echo command but do not stop ${...}
interpretation.You should be using an array for sinks_index
, not a scalar:
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.
Copy/paste your shell scripts into http://shellcheck.net til you get familiar with shell.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.