Reputation: 23
My script should get a string and print every char(including space,!@#$ etc.) in a new line
The script works on standart input but fails when some of the special chars appears in the string
here's my script
#!/bin/bash
if (($#!=1)); then
echo Please enter one string
exit 0
fi
string="$1"
num=`expr length $string`
for (( i=1; i<=num; i++ )); do
x=`expr substr $string $i 1`
echo "$x"
done
exit 0
Whats wrong?
Upvotes: 1
Views: 967
Reputation: 780673
Always quote your variables unless you WANT word splitting and wildcard expansion:
num=$(expr length "$string")
x=$(expr substr "$string" "$i" 1)
Upvotes: 1
Reputation: 784888
To print each character in BASH you can do this without calling any external utility:
for ((i=0; i<${#string}; i++)); do
echo "${string:i:1}"
done
Upvotes: 3