Reputation: 91
In a bash script I need to compare the first char of two Strings.
To do this, I use the head
operator like this:
var1="foo"
var2="doo"
headVar1=$(head -c1 $var1)
headVar2=$(head -c1 $var2)
if [ $headVar1 == $headVar2 ]
then
#miau
fi
But the console says "head: cant open foo for reading: Doesnt exist the file or directorie" And the same with doo
Some help?
Thanks.
Upvotes: 0
Views: 90
Reputation: 531215
A circuitous, but POSIX-compatible, solution:
var1="foo"
var2="doo"
headVar1=${var1%${var1#?}}
headVar2=${var2%${var2#?}}
if [ "$headVar1" = "$headVar2" ]
then
#miau
fi
${var1#?}
expands to the value of var1
minus its first character. That is used as the suffix to remove with ${var1%...}
, leaving in the end just the first character of var1
.
Upvotes: 0
Reputation: 241898
head
interpreted foo
as a filename. See man head
on what options are available for the command.
To store command output in a variable, use command substitution:
headVar1=$(printf %s "$var1" | head -c1)
which could be shortened using a "here string":
headVar1=$(head -c1 <<< "$var1")
But parameter expansion is much faster in this case, as it doesn't spawn a subshell:
headVar1=${var1:0:1}
Upvotes: 3
Reputation: 174706
Your code must be,
var1="foo"
var2="doo"
headVar1=$(head -c1 <<<"$var1")
headVar2=$(head -c1 <<<"$var2")
if [[ "$headVar1" == "$headVar2" ]]
then
echo "It's same"
else
echo "Not same"
fi
remove the space which exists next to equal sign (variable assignment part).
Use <<<
to fed input from a variable to the corresponding function.
Variable names must be preceded by the dollar $
symbol.
Upvotes: 1