Linux and Command-Line Basics
$ cat s.sh
#!/bin/bash
echo "$# $1"
$ ./s.sh a "b c" dAs shown above, the script s.sh is run with arguments. Which of the following is the output?
- A3 ./s.sh
- B3 a
- C4 a
Show answer and explanation
Answer: B. 3 a
Inside a script, $1, $2, ... are the first, second, ... arguments, $# is the number of arguments and $0 is the name of the script itself. "b c" is enclosed in double quotes, so it becomes one argument containing a space, and there are three arguments: a, b c and d. Therefore $# is 3 and $1 is a, and the output is 3 a. To pass all the arguments to another command while keeping them separate, "$@" is written.
- A. The name of the script is $0; $1 is the first argument, a.
- B. Correct. The three arguments are a, b c and d, and the first is a.
- C. The quoted "b c" is a single argument, so there are 3 arguments, not 4.