I'm trying to perform the following command, however it cannot read the variable assigned earlier. I'm not sure why this happen. Please help thanks
while :
do
echo "what's ur name? (if none just press [ENTER])"
read name
changeName = echo $name | sed "s/on/ey/"
echo $changeName #this variable still can be read
if [ -z $name ]; then
echo "you don't have a name goodbye"
exit 0
else
echo "your name will change from: $name to $changeName" #now changeName cannot be read why?
fi
done
To assign a command output to the variable you need to use the backtick(`).and also you should not give space while assign the output to a variable.
while :
do
echo "what's ur name? (if none just press [ENTER])"
read name
changeName=`echo $name | sed "s/on/ey/"`
echo $changeName #this variable still can be read
if [ -z $name ]; then
echo "you don't have a name goodbye"
exit 0
else
echo "your name will change from: $name to $changeName" #now changeName cannot be read why?
fi
done
I thing you have gave space characters in your input , to avoid this use the double quotes.
while :
do
echo "what's ur name? (if none just press [ENTER])"
read name
changeName=`echo "$name" | sed "s/on/ey/"`
echo $changeName #this variable still can be read
if [ -z "$name" ]; then
echo "you don't have a name goodbye"
exit 0
else
echo "your name will change from: $name to $changeName" #now changeName cannot be read why?
fi
done
thanks for the fast replies, even though i used double quotes it still doesn't wor and my input doesn't have any white spaces
here is the code suggested
#!/bin/sh
while :
do
echo "what's ur name? (if none just press [ENTER])"
read name
changeName= `echo "$name" | sed "s/on/ey/"`
echo $changeName #this variable still can be read
if [ -z "$name" ]; then
echo "you don't have a name goodbye"
exit 0
else
echo "your name will change from: $name to "$changeName" ? [y/n]"
read ans
fi
done
This is the ouput I got:
what's ur name? (if none just press [ENTER])
jon
./testVar: line 7: jey: command not found
#!/bin/sh
while :
do
echo "what's ur name? (if none just press [ENTER])"
read name
changeName=`echo "$name" | sed "s/on/ey/"`
echo $changeName #this variable still can be read
if [ -z "$name" ]; then
echo "you don't have a name goodbye"
exit 0
else
echo "your name will change from: $name to "$changeName" ? [y/n]"
read ans
fi
done
I just removed the space after the assignment
operator as in the below line and it is working for me...
changeName=`echo "$name" | sed "s/on/ey/"`
And it will keep on looping till you don't put a name...
Modern practice is to use '[[...]]' instead of '[...]' and '$(...)' instead of `...`
#!/usr/bin/bash
while read -p "what's ur name? (if none just press [ENTER])" name
do
if [[ -z "$name" ]]; then
echo "you don't have a name goodbye"
exit 0
fi
changeName=$(echo $name | sed "s/on/ey/")
echo "your name will change from: $name to $changeName"
done