Identify the amount and value of arguments received in a script

Asked

Viewed 100 times

0

How to identify the amount of arguments I received in a Bash script? How can I get past values?

2 answers

1


To know the amount of arguments the script received, use the variable $#. For example, if I have this script:

#!/bin/bash

echo $#

Assuming the script is in the file script.sh, if I call you so:

./script.sh a b c

The result will be 3, 3 arguments were passed (a, b and c).

You can even use it to test the amount of arguments. Ex:

# se quantidade de argumentos for diferente de 3, mostra mensagem
if [ "$#" -ne 3 ]; then
    echo "Só podem ter 3 argumentos"
fi

To get the argument values, you can use the variables $1, $2, etc.:

# imprime o primeiro argumento
echo $1
# imprime o segundo argumento
echo $2
# imprime o terceiro argumento
echo $3

If any of the arguments do not exist (for example, you tried to access $3 when the script only received 2 arguments), the value of the respective variable $n will be empty (and the respective echo print a blank line).


You can also make a loop by the arguments (without knowing the exact amount), using the variable $@:

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

Examples:

./script.sh a b c

Exit:

a
b
c

./script.sh a b 'c d'

Exit:

a
b
c d

0

Let’s say you have a script called status.sh that counts the words in a file. If you want to use this script on many files, it is best to pass the file name as an argument so that the same script can be used for all the files that will be processed.

then:

sh status.sh listamusica

The arguments are accessed within a script using the variables $ 1 , $ 2 , $ 3 and so on. The variable $ 1 refers to the first argument, $ 2 to the second argument and $ 3 to the third argument. This is illustrated in the following example:

FILE1 = $ 1 
wc $ FILE1

Here is an example of how to call this script with command line arguments:

sh status.sh listamusica1 lista de listamusica2 listamusica3

If an argument has spaces, put it in single quotes. For example:

sh status.sh 'lista de musicas 1' 'lista de musicas 2' 'lista de musicas 3'

Voce can continue to see more details on: https://www.lifewire.com/pass-arguments-to-bash-script-2200571

  • 1

    script.sh: 2: script.sh: FILE1: not found gave problem, I think because of the space.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.