bobbyiliev / introduction-to-bash-scripting

Free Introduction to Bash Scripting eBook

Home Page:https://ebook.bobby.sh

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature:

c4ir0 opened this issue · comments

commented

page 49 in the Loops lesson, the main code is

#!/bin/bash

read -p "What is your name? " name

while [[ -z ${name} ]]
do
    echo "Your name can not be blank. Please enter a valid name!"
    read -p "Enter your name again? " name
done

echo "Hi there ${name}"

could be shortened to :

#!/bin/bash

read -p 'what is ur name ? ' name

if [[ -z ${name} ]]
then
        echo 'please insert some name ...'
        $0
else
        echo hello, $name
fi

and THX ❤

@c4ir0


read -p "What is your name? " name

while [[ -z ${name} ]]
do
   echo "Your name can not be blank. Please enter a valid name!"
   read -p "Enter your name again? " name
done

echo "Hi there ${name}"

could make in a function :

askname(){  
#!/bin/bash  
read -p "What is your name? " name  
while [[ -z ${name} ]]  
do  
    echo "Your name can not be blank. Please enter a valid name!"  
    askname   
done
echo "Hi there ${name}"
}

therewith could by bad return value call it self as function (or how it names..)

as 0nelineer :

#!/bin/bash  
read -p 'what is ur name ? ' name ; if [[ -z ${name} ]] ; then  echo 'please insert some name ...' ; $0 ; else  echo hello, $name ; fi

saves the lines in a big bash script

best

Hey @c4ir0, thanks for this suggestion, but if we use $0 the script itself might not be executable or not in the path, resulting in the following error:

# bash test.sh
what is ur name ? 
please insert some name ...
test.sh: line 8: test.sh: command not found
commented

Hey @c4ir0, thanks for this suggestion, but if we use $0 the script itself might not be executable or not in the path, resulting in the following error:

# bash test.sh
what is ur name ? 
please insert some name ...
test.sh: line 8: test.sh: command not found

First, thx 4 reviewing my comment I just wanna clear some points :

  1. I have been learning bash scripting from just yesterday so I still learning and trying to apply what I have learnt (that is my state now)
  2. this is not considered to be enhancement of the code you wrote (since U used while and used if statement )
  3. Actually the code worked very fine with me but let me tell you why since was mentioned tat $0 refers to the file it self or the command used to run the file when u test (the last point was through my trials to but $0 in a script file and run it as $ ./test.sh once and $ bash test.shanother time )
    In another words the error will appear when u run the command with $ bash test.sh but when You try $ ./test.sh it will work very fine

Recording_1662723522381

This looks good! That is an interesting approach! Happy to see that you’ve been playing around and trying different things mentioned in the book and expanding on the information! Good luck with your studies!