1

Recently i got an assignment at school, where we are to write a small program in Bash Scripting Language.

This shell script is supposed to accept some Positional Parameters or Arguments on the command line.

Now, with the help of an if-else statement i check if the argument is present, if the argument is present the script does what it is supposed to do, but if the argument is not present - i display an error message, prompting the user to input an argument and pass the argument again to the same shell script...

Now, i want to know if this approach is good or bad in Bash Programming paradigm. I'm slightly suspicious that this might run too many tasks in the background that are kept open or that are never ended and keep on consuming memory... please help.

Here's a small snippet (assume the script name to be script1.bash):

 #!/bin/bash

 if [ $# -gt 0 ]; then
      read -p "Please enter your name: " name
      script1.bash $name
 elif [ $# -eq 1 ]; then
      echo "Your name is $1!"
 fi
3
  • 1
    You should include the homework tag if this is a school assignment. Commented Mar 1, 2011 at 3:43
  • @B Mitch - will take care of this from next time onwards.. Commented Mar 1, 2011 at 3:54
  • shell scripts running inside shell scripts? That's an abomination. Commented Mar 1, 2011 at 14:29

1 Answer 1

4

It's ... questionable :-)

The main problem is that you're spawning a subshell everytime someone refuses to input their name.

You would be better of with something like:

#!/bin/bash
name=$1
while [[ -z "$name" ]] ; do
    read -p "Please enter your name: " name
done
echo "Your name is $name!"

which spawns no subshells.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks paxdiablo, i've tried doing some becnhmarking using top command, nothing shows up their... just wondering???
Would his original code work if he used exec to do the recursive call?
Well, his original code works as-is (other than the fact it should be $1 rather than $name in the elif bit) unless you hit ENTER so many times the system runs out of processes. exec would stop that from happening. My answer was more along the lines of only do what's needed. There's no point in starting another process (or even replacing the contents of the current process a la exec) when you can just whip up a while loop.
thanks for your input. I realized i goofed up in the second part of if-else statement. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.