Output only non-empty arguments

Hello, I am VERY new to shell scripting here, so please go easy. I have an assignment that requires creating a script using bash shell, outputting all command line arguments that are not empty ones such as " ", and showing total number of arguments. I know how to show the total with $# and all arguments with $*, but is there a way to not output empty arguments? I am trying if statements and each time, the arguments appear as white spaces instead of not showing at all.

Can you please post an example how you call your script with the parameters and how your script itself looks?
When doing so, use

```text
 and 
```

around the code, data or logs to separate it from descriptive text for better readability and preserving indention etc.

#!/bin/sh 
if [ "$1" != "" ] then 
    echo "Argument 1: $1" 
     fi 
echo "arguments: [$*]" 
echo "Total number of command line arguments: $#"

Output:

"" 2 3 4
Argument 1: 
arguments: [ 2 3 4]
Total number of command line arguments: 4

I was just testing here with argument $1 and using random numbers as test arguments. There is the white space there before the 2.

#!/bin/sh

VAR=$(echo $*| sed 's/  / /g')
echo "arguments: [$VAR]"
echo "Total number of command line arguments: $#"

exit 0
1 Like

Do you really need to pass a space as an argument? That just does not sound right IMO. There are better ways to handle when arguments are not passed.

That seems to do the trick, zaxxon. Thank you. To frank - yes, it was required as part of the exercise.

For next time, just in case, keep that as a reminder please:

Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules.

Please review the rules, which you agreed to when you registered, if you have not already done so.

More-than-likely, posting homework in the main forums has resulting in a forum infraction. If you did not post homework, please explain the company you work for and the nature of the problem you are working on.

If you did post homework in the main forums, please review the guidelines for posting homework and repost.

Thank You.

The UNIX and Linux Forums.