Home > Software design >  How to print a special char using shell scripting
How to print a special char using shell scripting

Time:11-15

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

I want this output:

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

CodePudding user response:

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

CodePudding user response:

Put $list in double-quotes in the for loop. This stops the shell expansion that happens if no double-quotes are used and makes your list just a list of strings as you expect.

Note this is not to say there are not better shells and methods to use, just shows another way to be aware of :-)

$ cat x.sh
#!/bin/sh

list="bla1 bla2 * bla3"

for i in "$list"
do
    echo "$i"
done

$ ./x.sh
bla1 bla2 * bla3
  • Related