Issue
I'm trying to print some words stored in a list using for loop:
#!/bin/sh
list="bla1 bla2 * bla3"
for i in $list
do
echo "$i"
done
bla1
bla2
*
bla3
Running the script gives:
bla1
bla2
[LIST OF FILES]
bla3
I want the words stored in the list to be treated as strings, please HELP!
I tried:
echo "\$i"
echo ""$i""
echo "'$i'"
...
It does not work
Solution
Best practice when you need to store lists of arbitrary strings is to use a shell with support for arrays, rather than /bin/sh
:
#!/usr/bin/env bash
list=( bla1 bla2 "*" bla3 )
for i in "${list[@]}"; do
echo "$i"
done
...or use the one canonically-available array, the argument list:
#!/bin/sh
set -- bla1 bla2 "*" bla3
for i in "$@"; do
echo "$i"
done
Barring that, you can turn off glob expansion with set -f
, and turn it back on later (if you need) with set +f
:
#!/bin/sh
set -f # prevent * from being replaced with a list of filenames
list='bla1 bla2 * bla3'
for i in $list; do
echo "$i"
done
Answered By - Charles Duffy Answer Checked By - Gilberto Lyons (WPSolving Admin)