Linux and Command-Line Basics

$ cat s.sh
#!/bin/bash
echo "$# $1"
$ ./s.sh a "b c" d

As shown above, the script s.sh is run with arguments. Which of the following is the output?

  1. A3 ./s.sh
  2. B3 a
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. In a shell script, in which of the following cases is the condition of the if above true?
  2. Which of the following are the files in the directory after the session above?
  3. An executable script run.sh in the current directory gives "command not found" when run by typing "run.sh", but runs when typed as "./run.sh". Which of the following is the reason?
  4. When the commands above are run in order, which of the following is the pair of outputs of the two bash -c commands?
  5. Which of the following is the main function of a Linux package management system (apt on Debian-based systems, dnf on Red Hat-based systems and so on)?