1

Say I let a user input as many arguments as he wants, how do read all the inputs?

So if a user typed in asdf asfd asdf, it should say 3 arguments Right now I have

#!/bin/bash

read $@
echo "There are $# arguments"

but whenever I type in anything it always equals 0

5 Answers 5

1

If you want to read all the parameters from a variable using the same style as if you would have done it from the command line. You could do it in a function

#!/bin/bash

function param_count() {
   for arg in $@
   do
     echo " arg: $arg"
   done
   echo "arg count= $#"
}

read foo
param_count $foo
Sign up to request clarification or add additional context in comments.

Comments

1

If you really want to read a line as a sequence of words, your best bet in bash is to read it into an array:

$ read -a words
And now a few words from our sponsor
$ echo ${#words[@]}
8
$ echo "${words[3]}"
few

But that's not the way to pass arguments to a shell script. read just splits lines into words using whitespace (or whatever IFS is set to.) It does not:

  • Handle quotes
  • Allow the insertion of shell variables
  • Expand pathname patterns

Passing arguments on the command line lets you do all of the above, making the utility more convenient to use, and does not require any extra work to extract the arguments, making the utility easier to write.

Comments

0

This is the way to get it:

read ARGUMENTS
set -- $ARGUMENTS
echo "There are $# arguments"

Explanation:

read ARGUMENTS

Read the input and save it into ARGUMENTS


set -- $ARGUMENTS

Set the positional parameters to the given input


At this point, you can use that input as if it was given in the command-line.

e.g.:

echo "$1"
echo "$2"
...

Comments

0

Delete read $@ line. Then launch your script with arguments. Just like this:

/path/to/script arg1 arg2 arg3 4 5 6

The output should be:

There are 6 arguments

2 Comments

what if I wanted the user to type in inputs on a separate line?
Add simple loop to print all of them from script: for i; do echo $i; done Each argument can be accessed via: $1, $2, $3 ... $n
0

Here is an example script that shows you how to get the argument count, access the individual arguments and read in a new variable:

#!/usr/bin/env bash

echo "There are $# arguments, they are:"

for arg in $@
do
    echo "  - $arg"
done

# Access the aguments

echo "The first argument is $1"
echo "The second argument is $2"
echo "The third argument is $3"
echo "All arguments: $@"

# Read a variable

read var
echo "Some var: $var"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.